【问题标题】:Have a variable available for class __construct()有一个可用于类 __construct() 的变量
【发布时间】:2011-01-17 01:26:57
【问题描述】:
我正在尝试将变量传递给类,以便__construct() 可以使用它,但是在将任何变量传递给类之前调用__construct()。有没有办法在__construct() 之前发送变量?代码如下:
class Controller {
public $variable;
function __construct() {
echo $this->variable;
}
}
$app = new Controller;
$app->variable = 'info';
感谢您的帮助!
【问题讨论】:
标签:
php
oop
class
variables
【解决方案2】:
要么将变量作为参数传递给构造函数
function __construct($var) {
$this->variable = $var;
echo $this->variable;
}
//...
$app new Controller('info');
或者将构造函数完成的工作放在不同的函数中。
【解决方案3】:
您需要在构造函数定义中添加实参参数。
class TheExampleClass {
public function __construct($arg1){
//use $arg1 here
}
..
}
..
$MyObject = new TheExampleClass('My value passed in for constructor');
【解决方案4】:
+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 添加到类中,我就可以通过__construct 或init 设置此属性,只需将数据作为array('myProperty' => 'myValue') 之类的数组传入即可。此外,如果对象已使用isInitialized 方法“初始化”,我可以轻松地从外部逻辑进行测试。现在您可以做的另一件事是添加需要设置和过滤的“必需”属性列表,以确保在初始化或构造期间设置这些属性。它还为您提供了一种在给定时间设置一大堆选项的简单方法,只需调用init(或setOptions,如果您愿意)。
【解决方案5】:
class Controller {
public $variable;
function __construct() {
echo $this->variable;
}
}
$app = new Controller;
$app->variable = 'info';
您在构造后将“信息”分配给变量,
所以构造函数什么都不输出,
所以你必须在运行 echo 之前分配;
class Controller {
public $variable;
function __construct() {
$this->variable = "info";
echo $this->variable;
}
}
$app = new Controller();
现在你可以看到你想要的了;