2

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.

4
  • Don't initialize static variables in the constructor. The constructor function is for initializing new objects, a static property should be available on the class (without having called any constructor). Commented Nov 26, 2015 at 0:38
  • @CarlGroner Thanks for the comment. But I do not see why you are saying Don't initialize static variables in the constructor...It seems that it could be very beneficial at times. Could you explain? Commented Nov 26, 2015 at 0:53
  • I guess it's beneficial if you don't want the value to be available before an object of the class is created but I cant imagine many cases for that. Even if you want the constructor to modify the value, an explicit initial value would be better IMO. Commented Nov 26, 2015 at 1:07
  • @CarlGroner I see your point. I am happy to at least know how to use it if the need arises. Commented Nov 26, 2015 at 15:41

1 Answer 1

1

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"

Sign up to request clarification or add additional context in comments.

1 Comment

Just the right simplified answer I needed. Thank you Stah!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.