使用构造函数分配属性值和在类声明中直接分配属性有什么区别?换句话说,下面两段为新对象设置默认值的代码有什么区别?
直接赋值的代码:
<?php
class A {
public $name="aName";
public $weight = 80;
public $age = 25;
public $units = 0.02 ;
}
?>
带有构造函数的代码:
<?php
class A {
public $name;
public $weight;
public $age;
public $units;
public function __construct() {
$this->name = "aName";
$this->weight = 80;
$this->age = 25;
$this->units= 0.02 ;
}
}
?>
你可能会回答说我不能改变硬编码的属性,但我可以在下面的代码中(在本地服务器中):
<?php
class A{
public $name="aName";
public $weight = 80;
public $age = 25;
public $units = 0.02 ;
}
class B extends A{
public function A_eat(){
echo $this->name.' '."is".' '.$this->age.' '."years old<br>";
echo $this->name.' '."is eating".' '.$this->units.' '."units of food<br>";
$this->weight +=$this->units;
echo $this->name.' '."weighs".' '.$this->weight."kg";
}
}
$b = new B();
echo "<p>If no changes to the object's Properties it inherits the main class's</p>";
$b->A_eat();
echo '<br><br>';
echo "<p>If changes made to the object's Properties it uses it's new properties</p>";
$b->name ="bName";
$b->weight = 90;
$b->units = 0.05;
$b->A_eat();
?>
最佳答案
当属性声明包含初始化时,初始化在编译时进行计算,即在 PHP 源代码被编译成 PHP opcodes 的步骤中.
构造函数中的代码在运行时 求值,即在使用new
运算符创建对象时求值。
如果您不使用操作码缓存(OPcache、APC 和类似扩展),实际上没有区别。但是,如果操作码被缓存,显然编译时初始化的性能会更好。
关于php - 使用构造函数分配属性值和在类声明中分配属性有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40944829/