Calling static class member in PHP - php

I am trying to get a variable from a php class without having to use "new classname()"
This is my code:
class myVars {
static $varx = null;
public function __construct() {
$this->varx = "test";
}
}
echo myVars::$varx;
I also tried replacing $this-> with self::, but nothing gets printed. How should I code the class in order to call myVars::$varx?

The problem you are having, is that you are not instantiating an object, so the constructor never gets called.
What you could do is:
class myVars {
static $varx = null;
public function __construct() {
$this->varx = "test";
}
}
myVars::$varx = "test";
echo myVars::$varx;
Or you could create an object and have the constructor change the static variable.

This should make your static variable publicly accessible.
class myVars {
public static $varx = null;
public function __construct() {
self::$varx = "test";
}
}
echo myVars::$varx;
However, in your example, the constructor is never called, so the modification to the static variable is never made.

Related

PHP OOP - Accessing property value is returning empty

I have the following class, and for some reason it's not accessing the test property. Why is this? I'm new to OOP, so please be easy on me. Thanks
class Test {
private $test;
function __contruct() {
$this->test = "test";
}
static function test() {
echo $this->test;
}
}
$test = new Test;
$test::test();
Because static methods are callable without an instance of the object
created, the pseudo-variable $this is not available inside the method
declared as static.
PHP Documentations.
Good morning.
It seems you have 3 issues with your code.
There is a syntax error at constructor line change it from __contruct to __construct.
Change test function visibility to public
Access your function with the -> instead of ::
To elaborate further on the above answers: Static methods and variables are not linked to any particular instance of the object, this is why you have to call test with $test::test(). This also means that you cannot access an instance variable from without a static method and it doesn't really make sense to do so (If you had multiple instances of the object with different values set for that variable, how would the interpreter know which instance/value to use?)
If you want to have a field accessible from a static method then you have to make the field static as well. So, if you wanted to have $test accessible from your static method test() then you'd have to write your function as something along these lines:
class Test {
private static $test;
function __contruct() {
Test::$test = "test";
}
public function test() {
echo Test::$test;
}
}
$test = new Test;
$test::test();
However, it doesn't really make sense to be initialising a static field like that in your constructor. So you'd more likely be wanting to do something like:
class Test {
private static $test = "test";
function __contruct() {
}
public static function test() {
echo Test::$test;
}
}
$test = new Test;
$test::test();
Or, if you don't actually require test() to be static then you could just make it an instance method:
class Test {
private $test = "test";
function __contruct() {
$this->$test = "test"
}
public function test() {
echo $this->$test;
}
}
$test = new Test;
$test->test();

Php get variable from required file

I have a class:
class My_Class {
private $playlist_table_name;
public function __construct() {
$this->playlist_table_name = "something";
require_once('markup.php');
}
}
How do I access $playlist_table_name from markup.php file?
I tried using: $this->playlist_table_name, but I get:
Using $this when not in object context
If you want to access the variable like that, you will need to mark it as public
class My_Class {
public $playlist_table_name;
public function __construct() {
$this->playlist_table_name = "something";
require_once('markup.php');
}
}
You are then going to want to instantiate the class before attempting to use it.
$MyClass = new My_Class;
echo $MyClass->playlist_table_name;
That will allow you to echo out the value.

How do I use objects and access their methods while within an object in PHP?

How do I use an object (along with its methods and properties) when I'm inside an object?
Say I have useless classes like these:
class Fruit {
private $name; // Name of the fruit.
private $health = 10; // 0 is eaten, 10 is uneaten.
private $object; // This is a PHP object.
public function __construct($name) {
$this->name = $name;
}
public function set($varname,$value) {
$this->$varname = $value;
}
}
class Eater {
private $name;
public function eat($object) {
$object->set('health',0); // I know I can pass and modify objects like this.
// The object is passed by reference in PHP5 (but not 4), right?
}
}
And I use it as such:
<?php
$pear = new Fruit("Pear");
$apple = new Fruit("Apple");
$paul = new Eater("Paul");
$paul->eat($apple);
?>
But if I modify the Eater class like so:
class Eater {
private $name;
private $objectToEat; // Let's say if I need the object to be over here instead of in a method.
public function set($varname,$value) {
$this->$varname = $value;
}
public function eat() {
$this->objectToEat->set('health',0); // This doesn't work!
}
}
And set the main program like so:
<?php
$pear = new Fruit("Pear");
$apple = new Fruit("Apple");
$paul = new Eater("Paul");
$paul->set('objectToEat',$apple);
$paul->eat();
?>
How can I access the object's properties from inside a method? I know I use $this->objectToEat to tell PHP I'm talking about the class properity, but since that property is an object, how do I access the object's methods?
I've tried $this->objectToEat->set('health',0) but that doesn't work. I hope you guys understand what I'm trying to get at (sorry, I can't figure out how to condense my question without compromising clarity)!
You have to set the property correctly. Since it's private, you can't do this from outside the object, so you have to use encapsulation:
class Eaters {
private $name;
private $objectToEat;
public function eat() {
$this->objectToEat->set('health',0); // Assumed "object" was just a typo
}
public function setObjectToEat($object) {
$this->objectToEat = $object;
}
}
Then use it like so:
<?php
$pear = new Fruit("Pear");
$apple = new Fruit("Apple");
$paul = new Eater("Paul");
$paul->setObjectToEat($apple);
$paul->eat();
?>
Note: In this brief example, your original method is a better design. In certain cases, you might want to prime the method to be used by setting properties beforehand, but more often you want to call it with parameters directly, since it's more clear and more reusable (compartmentalized).
This answer modifies Renesis' answer
In the class, the object to eat is a private variable hence you can't go
$paul->objectToEat = $apple;
What you can do is to make a setter method inside Eaters
class Eaters {
private $name;
private $objectToEat;
public function eat() {
$this->objectToEat->set('health',0); // Assumed "object" was just a typo
}
public function setFood($object) {
$this->objectToEat = $object;
}
}
Therefore, you can call the setFood() method instead.
OR
Change eat() to
public function eat($object) {
$this->object->set('health',0);
return $object;
}
Saving the modified object back to the original variable.
OR
class Eaters {
private $name;
public function eat(&$object) { // this passes object by reference
$object->set('health', 0);
}
}
Although this code is not tested, that is how you can pass a variable by reference.
NOTE: You only need the & when defining the method not when you're passing an argument. For more info about Passing by Reference go to this link
It's probably because your eat method isn't accepting any parameters, and the Eaters class has no $object property.
Can you make $objectToEat a reference and then use it as such in the eat() function?
you have to set $this->object in class Eaters
function __construct($object){
$this->object = $object;
}
or
<?php
$pear = new Fruit("Pear");
$apple = new Fruit("Apple");
$paul = new Eater("Paul");
$paul->eat($apple);
?>
class Tester {
private $variable;
private $anObj;
public function testFn($val) {
$this->variable = $val;
$this->anObj = new SecondObj();
$this->doSomething();
}
public function doSomething() {
echo("My variable is set to " . $this->variable);
$this->anObj->wow();
}
}
class SecondObj {
public function __construct() {
echo("I'm new!");
}
public function wow() { echo("Wow!"); }
}
$tester = new Tester();
$tester->testFn(42);
Output:
I'm new!My variable is set to 42Wow!

PHP class: Global variable as property in class

I have a global variable outside my class = $MyNumber;
How do I declare this as a property in myClass?
For every method in my class, this is what I do:
class myClass() {
private function foo() {
$privateNumber = $GLOBALS['MyNumber'];
}
}
I want this
class myClass() {
//What goes here?
var $classNumber = ???//the global $MyNumber;
private function foo() {
$privateNumber = $this->classNumber;
}
}
EDIT: I want to create a variable based on the global $MyNumber but
modified before using it in the methods
something like: var $classNumber = global $MyNumber + 100;
You probably don't really want to be doing this, as it's going to be a nightmare to debug, but it seems to be possible. The key is the part where you assign by reference in the constructor.
$GLOBALS = array(
'MyNumber' => 1
);
class Foo {
protected $glob;
public function __construct() {
global $GLOBALS;
$this->glob =& $GLOBALS;
}
public function getGlob() {
return $this->glob['MyNumber'];
}
}
$f = new Foo;
echo $f->getGlob() . "\n";
$GLOBALS['MyNumber'] = 2;
echo $f->getGlob() . "\n";
The output will be
1
2
which indicates that it's being assigned by reference, not value.
As I said, it will be a nightmare to debug, so you really shouldn't do this. Have a read through the wikipedia article on encapsulation; basically, your object should ideally manage its own data and the methods in which that data is modified; even public properties are generally, IMHO, a bad idea.
Try to avoid globals, instead you can use something like this
class myClass() {
private $myNumber;
public function setNumber($number) {
$this->myNumber = $number;
}
}
Now you can call
$class = new myClass();
$class->setNumber('1234');
Simply use the global keyword.
e.g.:
class myClass() {
private function foo() {
global $MyNumber;
...
$MyNumber will then become accessible (and indeed modifyable) within that method.
However, the use of globals is often frowned upon (they can give off a bad code smell), so you might want to consider using a singleton class to store anything of this nature. (Then again, without knowing more about what you're trying to achieve this might be a very bad idea - a define could well be more useful.)
What I've experienced is that you can't assign your global variable to a class variable directly.
class myClass() {
public $var = $GLOBALS['variable'];
public function func() {
var_dump($this->var);
}
}
With the code right above, you get an error saying "Parse error: syntax error, unexpected '$GLOBALS'"
But if we do something like this,
class myClass() {
public $var = array();
public function __construct() {
$this->var = $GLOBALS['variable'];
}
public function func() {
var_dump($this->var);
}
}
Our code will work fine.
Where we assign a global variable to a class variable must be inside a function. And I've used constructor function for this.
So, you can access your global variable inside the every function of a class just using $this->var;
What about using constructor?
class myClass {
$myNumber = NULL;
public function __construct() {
global myNumber;
$this->myNumber = &myNumber;
}
public function foo() {
echo $this->myNumber;
}
}
Or much better this way (passing the global variable as parameter when inicializin the object - read only)
class myClass {
$myNumber = NULL;
public function __construct($myNumber) {
$this->myNumber = $myNumber;
}
public function foo() {
echo $this->myNumber;
}
}
$instance = new myClass($myNumber);
If you want to access a property from inside a class you should:
private $classNumber = 8;
I found that globals can be used as follows:
Create new class:
class globalObj{
public function glob(){
global $MyNumber;
return $this;
}
}
So, now the global is an object and can be used in the same way:
$this->glob();
class myClass
{
protected $foo;
public function __construct(&$var)
{
$this->foo = &$var;
}
public function foo()
{
return ++$this->foo;
}
}

Object properties

Is the only way to assign $systime a value of a built-in-functions, is through a method?
class Test{
private $systime;
public function get_systime(){
$this->systime = time();
}
}
Right off i would think something like this right?:
class Test{
private $systime = time();
public function get_systime(){
echo $this->systime;
}
}
Thanks
You should be able to use a constructor to assign the value, for example:
class Test {
private $systime;
function __construct() {
$this->systime = time();
}
public function get_systime(){
echo $this->systime;
}
}
$t = new Test();
$t->get_systime();
For more information on __construct() see the php manual section on object oriented php.
From http://www.php.net/manual/en/language.oop5.basic.php (Just before Example 3)
The default value must be a constant
expression, not (for example) a
variable, a class member or a function
call.
However, you can also assign a value from the constructor:
class Test{
private $systime;
public function __construct(){
$this->systime = time();
}
public function get_systime(){
echo $this->systime;
}
}

Categories