如何在php中使用构造函数来初始化实例变量
问题描述:
我知道这是一个常见问题,但我看到的问题(约10)比我一直困惑。如何在php中使用构造函数来初始化实例变量
我的问题包含在代码中作为注释。
我有三个字段
public class Model
{
public $prop1;
public $prop2;
public $prop3;
public function _construct($params) // doubt 1: Do I have to pass an array to a constructor, can't I pass the parameters individually
{
// doubt 2: How to assign the value to the instance variables
}
}
$model = new \App\Model($whatToPuthere); //doubt 3: How to provide the constructor parameters
答
正确的方法去做一类是这样的:
public class Model
{
public $prop1;
public $prop2;
public $prop3;
public function __construct($prop1, $prop2, $prop3)
{
$this->prop1 = $prop1;
$this->prop2 = $prop2;
$this->prop3 = $prop3;
}
}
$model = new \App\Model("prop1_value", "prop2_value", "prop3_value");
答
你是非常接近,访问当前实例变量,你需要使用$this
。您还需要为构造方法使用2个下划线。除此之外,将它视为另一个功能。
class Model {
public $prop1;
public $prop2;
public $prop3;
public function __construct($prop1, $prop2, $prop3) {
$this->prop1 = $prop1;
$this->prop2 = $prop2;
$this->prop3 = $prop2;
}
}
$model = new \App\Model("prop1", "prop2", "prop3");
答
它是由你来决定什么是你\App\Model
类用户使用更方便。这是一个使用固定数量属性的例子。
class Model
{
public $prop1;
public $prop2;
public $prop3;
public function __construct($prop1, $prop2, $prop3)
{
$this->prop1 = $prop1;
$this->prop2 = $prop2;
$this->prop3 = $prop3;
}
}
$model = new \App\Model('Property 1', 'Property 2', 'Property 3');
如果你打算使用动态数量的属性,你应该考虑使用数组作为参数。
class Model
{
public $prop1;
public $prop2;
public $prop3;
public function __construct(array $properties)
{
$this->prop1 = $properties['prop1'];
$this->prop2 = $properties['prop2'];
$this->prop3 = $properties['prop3'];
}
}
$model = new \App\Model(
array('prop1' => 'Property 1', 'prop2' => 'Property 2', 'prop3' => 'Property 3')
);
+1
'公共课程'无效! –
你读过关于[类和对象](http://php.net/manual/en/language.oop5.php)的PHP文档吗?现在您需要知道的所有内容都在这里进行了解释,并附有示例。 – axiac
有一个关于一切的文档“如果我们遵循这种思路,没有理由有*,如果我停下来阅读我面对的每一个问题的文档,将需要很长的时间来完成我的任务。我的问题是非常基本的应该有一个概念,但在这一刻我没有时间阅读文档 –
除了我阅读文档,但我也感到困惑它。PHP中的构造函数对我来说很困惑,你应该有询问我是否阅读了文档,在downvote之前! –