This page explains Three uses of the double colon :: in OOP.

Example 1:

Using the double colon :: with Constructors and Inheritance.

You can use the double colon :: in the construct method to pass data back to the base class's constructor:

If you have two classes Person and Friend that was inherited from the person class and want to pass data back to the base (Person) class's constructer. Eg.

<?php
class Person
{
    var 
$name;
    function 
__construct($data)
    {
        
$this -> name $data;
    }

}

class 
Friend extends Person
{
    var 
$message;
    function 
set_message($msg)
    {
        
this->message =$message;
    }
    function 
speak()
    {
        echo 
$this-> message;
    }
}
?>

You can do that by adding parent::__construct in the Friend class's constructor. Eg.


<?php
    
function __construct($data)
    {
        
parent::__construct($data);
    }
?>

and you can pass other data to the constructer as well and data targeted for the Friend class. Eg:


<?php
class friend extends Person
    
var $message;
    
    function 
__construct($data,$msg)
    {
        
parent::__construct($data);
        
$this->message =$msg;
    }
    function 
speak()
    {
        echo 
$this-> message;
    }
}
$greame= new friend("Greame","Hi,How are you.");
?>

Example 2:

If you want access to a class's base methods thats protected you can call and change it with the parent:: syntax:eg:


<?php
class Person
{
    var 
$name;
    protected function 
set_name($data)
    {
        
$this -> name $data;
    }

}

class 
friend extends Person
    
var $message;
    
    function 
set_message($msg)
    {
        
parent::__construct($data);
        
$this->message =$msg;
    }
    function 
speak()
    {
        echo 
$this-> message;
    }
    
// calls the protected methods and sets it to the new value
    
function set_name_public($data)
    {
        
parent::set_name($data);
    }
}

?>

Example 3:

You can use the double colon :: to call static methods eg:

 


<?php
class Math
{
    public static 
fuction say_hi()
    {
        echo 
"This class says hi.<br>");
    }
}
echo 
"using the math class...<br>");
Math::say_hi();
?>

Free Web Hosting