Home    Articles

 

How to use classes in php, part 2. The constructor and member variables.

 

Hi again.
In the first part we saw how to declare the class.Now we will see how to use the constructor and member variables.

The code:

<?php 
class validator 
{     
    public $valid_email;     
    public function __construct()     
    {     
       $this->valid_email = FALSE;
    } 
} 
?>

The variable $valid_email will be used in order to check if the latest checked email is valid.
When the class is initialized, the $valid_email is initialized with FALSE value.

This initialization isn’t necessary to be made in constructor. Can be made on the line where the variable was declared : public $valid_email = FALSE;

Instantiating the class:

<?php 
class validator 
{     
    public $valid_email;     
    public function __construct()     
    {     
       $this->valid_email = FALSE;
       // the line bellow can be used to see if the constuctor is automaticly called.
       //echo 'the constructor was called';exit;
    } 
} 
?>
//here we have instantiated validator class
$validator = new validator();

In the next part we will build a method that will validate an email adderss and will update the $valid_email member variable.

by