views:

94

answers:

4

I am trying to pass a variable into a class so the __construct() can use it however the __construct() is called before any variables are passed to the class. Is there any way to send the variable before the __construct()? Here is the code:

class Controller {
public $variable;

function __construct() {
    echo $this->variable;
}

}

$app = new Controller;
$app->variable = 'info';

Thanks for your help!

+1  A: 

The constructor can get parameters and you can initialize properties ...

class Controller {
    public $variable = 23;

    function constructor($othervar) {
        echo $this->variable;
        echo $othervar;
    }
}

$app = new controller(42);

Prints 2342.See the PHP documentation. http://php.net/manual/en/language.oop5.decon.php

johannes
+2  A: 

Either pass the variable as an argument to the constructor

function __construct($var) {
    $this->variable = $var;
    echo $this->variable;
}
//...
$app new Controller('info');

Or put the work done by the constructor in a different function.

Yacoby
+1  A: 

You need to add argument parameters to the constructor definition.

    class TheExampleClass {
       public function __construct($arg1){
          //use $arg1 here
       }
    ..
    }

..

$MyObject = new TheExampleClass('My value passed in for constructor');
jellyfishtree
+1  A: 

+1 Yacoby's general answer. As far as his hint about moving the logic into another method i like to do something like the following:

class MyClass
{
    protected $_initialized = false;

    public function construct($data = null)
    {
        if(null !== $data)
        {
            $this->init($data);
        }
    }

    public function init(array $data)
    {
         foreach($data as $property => $value)
         {
              $method = "set$property";
              if(method_exists($this, $method)
              {
                   $this->$method($value);
              }

              $this->_initialized = true;
          }

          return $this;
    }

    public function isInitialized()
    {
         return $this->_initialized;
    }
}

Now by simply adding a setMyPropertyMEthod to the class i can then set this property via __construct or init by simply passing in the data as an array like array('myProperty' => 'myValue'). Further more i can easily test from outside logic if the object has been "initialized" with the isInitialized method. Now another thing you can do is add a list of "required" properties that need to be set and filter to make sure those are set during initialization or construction. It also gives you an easy way to set a whole bunch of options at a given time by simply calling init (or setOptions if you prefer).

prodigitalson