在类声明中使用构造函数和直接属性赋值分配属性值有什么区别?换句话说,以下两段代码为新对象创建默认值有什么区别?在类声明中使用构造函数和属性赋值分配属性值有什么区别?
代码直接分配:
<?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 ;
}
}
?>
你可能会回答,我不能改变硬编码的性能,但我可以在下面的代码(在Local Sever):
<?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();
?>
这里有什么问题?对于一个你的构造方法是不正确的,你错过了你的支架括号减速,为什么你会公开一些东西,如果你使用一个方法来访问它在setter/getter? – KDOT
您的示例中充满了语法错误(例如'$ weight->')。这就是说,你不能在没有构造函数的情况下动态设置值。 – Qirel
这是我的错误,我添加了括号。但我的问题是为什么要使用构造函数,我可以给该属性声明中的默认值?..请忘记语法。 –