2

I'm having issues accessing a property inside a constructor:

Class MyClass{

    public $stuff   = false;

    public function __construct(){
        if($this->stuff){ echo('It works!'); }
    }

}

Called via:

$myclass = new MyClass;
$myclass->stuff = true;

It still returns false (hence no "It Works!").

I know the constructor isn't going to see the variable, but is there a good method for achieving this?

2 Answers 2

3

The constructor is called before you set the property. The if will always evaluate false.

If you want to set MyClass::stuff, set it via a constructor argument, for example:

public function __construct($stuff = false){
    if($this->stuff = $stuff){
        echo('It works!');
    }
}
$myclass = new MyClass(true);
Sign up to request clarification or add additional context in comments.

Comments

0

I don't see the point of $stuff

public $stuff   = false;

An instance variable which is set to false and checked immediately inside your constructor. This variable will not change unless it's instantiated. I think what you may have been looking for is a static variable.

Class MyClass{

    public static $stuff = false;

    function __construct(){ // you don't have to specify the constructor as public
        if (self::$stuff){ 
           echo 'You got some stuff!'; 
        } else { 
           echo 'You ain\'t got stuff!'; 
        }
    }

}


$myclass = new MyClass(); // You ain't got stuff!


MyClass::$stuff = true;
$myclass = new MyClass(); // You got some stuff!

if it was intended to be an instance variable, the only time you need this would be when subclassing

Class MyClass{

    public $stuff = false;

    function __construct(){ 
        if ($this->stuff){ 
           echo 'You got some stuff!'; 
        } else { 
           echo 'You ain\'t got stuff!'; 
        }
    }

}


class MySubClass extends MyClass {    
    public $stuff = true;    
}


$mysub = new MySubClass() // You got some stuff! 

If you just want to pass stuff to the constructor, why even define an instance variable? Shouldn't the following be sufficient? unless you have to refer to it later, in which case, Tim Cooper's answer.

Class MyClass {

   function __construct($stuff = false){
      if ($stuff){ 
         echo 'You got some stuff!'; 
      } else { 
         echo 'You ain\'t got stuff!'; 
      }
   }
}

Comments

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.