Construct


computer apg

All objects can have a special built-in method called a constructor that allow we to initialize the object's properties whem we instantiate an object.



 __construct 


The construct method name, (function), starts with two underscores and ends with the word construct.

A constructor allows we to initialize an object's properties upon creation of the object.

If we create a __construct function, PHP will automatically call this function when we create an object from a class.

In the next exercise, we find that by using the __construct function we save coding because such a function allows no set_... functions to be used.



  1 EXERCISE   

<?php

class Dwarfs {
    
    
/* Properties */
    
public $name;
    public 
$behavior;
    public 
$friend;
    public 
$age;

    
    
/* Methods */
    
function __construct($name$behavior$friend$age
    {
    
$this->name $name;
    
$this->behavior $behavior;
    
$this->friend $friend;
    
$this->age $age;
    }
    
    public function 
get_name() 
    {
    return 
$this->name;
    }
    public function 
get_behavior() 
    {
    return 
$this->behavior;
    }
    public function 
get_friend() 
    {
    return 
$this->friend;
    }
    public function 
get_age() 
    {
    return 
$this->age;
    }    
        
        
}
$nm 'Happy';
$bh 'This dwarf is always cheerful and happy about everything.';
$fr 'Snow White friend';
$ag '1937 - Year of the first performance of "Snow White and the Seven Dwarfs"';

$dwarf = new Dwarfs($nm$bh$fr$ag);

echo 
$dwarf->get_name();
echo 
'<br><br>';
echo 
$dwarf->get_behavior();
echo 
'<br><br>';
echo 
$dwarf->get_friend();
echo 
'<br><br>';
echo 
$dwarf->get_age();
echo 
'<br><br>';
     
?>

 RESULT   

Happy

This dwarf is always cheerful and happy about everything.

Snow White friend

1937 - Year of the first performance of "Snow White and the Seven Dwarfs"



These results, with the use of the __construct function, do not depend on implementing set_... type functions.