What is the difference between assigning property values using a constructor and direct property assignment within the class declaration? In other words, what is the difference between the following two pieces of code making default values for the new object?
Code with direct assignment:
<?php
class A {
public $name="aName";
public $weight = 80;
public $age = 25;
public $units = 0.02 ;
}
?>
Code with constructor:
<?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 ;
}
}
?>
You may answer that i can't change the hard coded properties, but i could in the following code( In 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();
?>
When a property declaration contains initialization, the initialization is evaluated at compile time, i.e. in the step when the PHP source is compiled into PHP opcodes.
The code within constructor is evaluated at run time, i.e. at the time when one creates an object with new
operator.
There is practically no difference, if you don't use opcode caching (OPcache, APC, and similar extensions). However, if the opcodes are cached, the performance will be better with the compile-time initialization, obviously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With