2010-02-15 23 views
1

我想将一个变量传递给一个类,所以__construct()可以使用它,但是在将任何变量传递给该类之前调用​​__construct()。有没有办法在__construct()之前发送变量?这里是代码:有一个变量可用于类__construct()

class Controller { 
public $variable; 

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

} 

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

感谢您的帮助!

回答

1

+1 Yacoby的一般答案。至于他对逻辑移动到另一个方法暗示我喜欢做的事情如下所示:

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; 
    } 
} 

现在,通过简单地增加setMyPropertyMEthod到类,然后可以通过__constructinit只需通过设置该属性在数据中,像array('myProperty' => 'myValue')这样的数组。进一步,我可以很容易地从外部逻辑测试,如果对象已经用isInitialized方法“初始化”。现在你可以做的另一件事是添加一个需要设置的“必需”属性列表并进行筛选,以确保在初始化或构建过程中设置这些属性。它还为您提供了一种简单的方法,通过简单地拨打init(或如果您愿意的话可以使用setOptions),在给定时间设置一大堆选项。

4

构造可以得到的参数,你可以初始化属性...

class Controller { 
    public $variable = 23; 

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

$app = new controller(42); 

打印2342.See PHP文档。 http://php.net/manual/en/language.oop5.decon.php

2

无论是通过变量作为参数传递给构造

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

或把由构造在不同的功能所做的工作。

1

您需要将参数参数添加到构造函数定义中。

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

.. 

$MyObject = new TheExampleClass('My value passed in for constructor'); 
1
class Controller { 
    public $variable; 

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

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

分配“信息”建设后的变量, 所以构造函数输出什么, 所以你必须运行回声之前分配;

class Controller { 
    public $variable; 
    function __construct() { 
     $this->variable = "info"; 
     echo $this->variable; 
    } 
} 

$app = new Controller(); 

现在你可以看到你想要的东西;

相关问题