Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP global variable inside a class

Let's say I have a class Bla that contains the variable $x.

I want this variable $x to keep its value for other objects once it's set by the first created object.

For example:

$object1 = new bla(.....);
$object1->setx();
$object1->getx();

$object2 = new bla(.....);
$object2->getx();

So I want:

 $object2->getx()

...to give me the value I already set by object1.

I tried using $x as a globale variable inside the class, it turns out that it's not possible. Can I use it outside the class and then access this variable inside the class?

What are the other methods?

like image 847
maggie Avatar asked May 11 '26 14:05

maggie


1 Answers

Use static variables if you want them to have one and the same value, available regardless of their class instances (tutorial):

class bla
{
    private static $x;

    public function setx($x) {
        self::$x = $x;
    }

    public function getx() {
        return self::$x;
    }
}

$object1 = new bla();
$object1->setx(5);
echo $object1->getx();
echo '<br>';

$object2 = new bla();
echo $object2->getx();

Output:

5
5

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!