在類聲明中使用構造函數和直接屬性賦值分配屬性值有什麼區別?換句話說,以下兩段代碼爲新對象創建默認值有什麼區別?在類聲明中使用構造函數和屬性賦值分配屬性值有什麼區別?
代碼直接分配:
<?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
這是我的錯誤,我添加了括號。但我的問題是爲什麼要使用構造函數,我可以給該屬性聲明中的默認值?..請忘記語法。 –