我已经搜索了一段时间,但是我找不到答案,这两种方法在PHP中不划分的变量类别有什么区别?::(如果有)
class MyClass
{
private $myVariable='something';
public function __construct()
{
}
}
class MyClass
{
private $myVariable;
public function __construct()
{
$this->myVariable='something';
}
}
- 如果要使用默认值 inside the Class初始化变量,请选择方法1.
- 如果要用a 外部值初始化变量,请通过构造函数传递变量,然后选择方法2。
请参阅此方案:
class Parent {
protected $property1; // Not set
protected $property2 = '2'; // Set to 2
public function __construct(){
$this->property1 = '1'; // Set to 1
}
} // class Parent;
class Child extends Parent {
public function __construct(){
// Child CHOOSES to call parent constructor
parent::__construct(); // optional call (what if skipped)
// but if he does not, ->property1 remains unset!
}
} // class Child;
这是两个调用之间的区别。父:: __ construct()是从父母继承的子类的可选。所以:
- 如果您有标量(如
is_scalar()
中的)它们也存在于儿童课程中。 - 如果您依赖参数或可选的属性,请将它们放入构造函数。
这一切都取决于您如何设计代码的功能。
这里没有错,这只是您的正确权利。
我喜欢这样做类似于促进懒惰加载的第二种方法。声明成员变量时将设置的简单值。
class WidgetCategory
{
/** @var array */
private $items;
/**
*
* @return array
*/
public function getItems()
{
if (is_null($this->items)) {
$this->items = array();
/* build item array */
}
return $this->items;
}
}
您只能使用常数值,如果您不选择初始化构造函数中的变量。这里有一个例子:
define('MY_CONSTANT', 'value');
class MyClass
{
// these will work
private $myVariable = 'constant value';
private $constant = MY_CONSTANT;
private $array = Array('value1', 'value2');
// the following won't work
private $myOtherVariable = new stdClass();
private $number = 1 + 2;
private $static_method = self::someStaticMethod();
public function __construct($param1 = '')
{
$this->myVariable = $param1;
// in here you're not limited
$this->myOtherVariable = new stdClass();
$this->number = 1 + 2;
$this->static_method = self::someStaticMethod();
}
}
请查看此手册页面,以查看允许直接调节属性的值:http://php.net/manual/manual/en/language.oop.properties.properties.php
可能有更多差异...