简体   繁体   中英

PHP Construct with Static Variable

I am racking my brain here. Just when I think I am understanding something, I am proven wrong.

My question involves using a static method, static variable, and the __construct magic method. Let's look at this example

<?php

class DummyStatic
{
    public static $variable;

    public function __construct()
    {
        self::$variable = 'Dummy Text';
    }

    public static function text()
    {
        return self::$variable;
    }   

}

$dummyText = DummyStatic::text();

?>

I was under the assumption that when I call DummyStatic::text(); that it would return Dummy Text .

I am using an MVC in another project where something like this is being done with success but why it doesn't work being stand alone is driving me crazy.

Any thoughts?

Thank you in advance.

It does not return "Dummy Text" because the constructor was never executed. The constructor is only executed on a new instance of the class.

$foo =  new DummyStatic();
echo DummyStatic::text();

This would, however, print out "Dummy Text"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM