Scope Resolution Operator In PHP – Info PHP
Introduction
This article explains the scope resolution operator in OOP using PHP5. The scope resolution operator, or in less complicated terms, the double colon, may be a token that permits access to static, constant, and overridden properties or ways of a category. When referencing these things from outside the category definition, use the name of the category. As of PHP 5.3, it is possible to reference the category employing a variable. The variable can’t be a keyword such as the self keyword, parent and static keyword. At first, it looks like an odd selection for naming a double-colon.
The most common use for scope resolution is with the pseudo-class “parent”. As an example, if you wish a child object to determine its parent’s “__construct()” operater then you use “parent::__construct()”. The scope resolution operator sometimes is useful to refer to functions and variables in base classes.
Example
class demo {
function test() {
echo “this own function demo::test().’
‘”;
}
}
class newclass extends demo {
function test() {
echo “this is modified functio newclass::test().’
‘”;
demo::test();
}
}
demo::test();
$a = new newclass;// include the outside demo class
$a->test();
?>
Output
Example
Three special keywords self, parent and static square measure won’t access properties or ways from within the category.
class demo
{
const static_value = ‘A constant value’;
}
$demoname = ‘demo’;
echo $demoname::static_value.“
“;
echo demo::static_value.“
“;
?>
Output
Example
In this example we use “demo” outside the class. When an associated extending category overrides the oldsters definition of a technique, PHP won’t determine the parent’s technique. It’s up to the extended category to determine whether or not the parent’s technique is termed. This additionally applies to Constructors and Destructors, Overloading, and Magic technique definitions.
include ‘demo.php’;// include the outside demo class
class newclass extends demo// extend the outside demo class
{
public static $var = ‘static var’;
public static function exa()
{
echo parent::static_value . “
“;
echo self::$var .“
“;
}
}
$demoname = ‘newclass’;
echo $demoname::exa();
newclass::exa();
?>
Output
Example
This example show calling a parent’s method.
class demo
{
protected function hello()
{
echo “demo::hello()”.“
“;
}
}
class newclass extends demo
{
// Override parent’s definition
public function hello()
{
// But still call the parent function
parent::hello();
echo “newclass::hello()”.“
“;
}
}
$test = new newclass();
$test->hello();
?>
Output
Article Prepared by Ollala Corp