In Php, static properties and methods are inherited. If you update the value of a static property same will be reflected to all the subclasses and this class.
static_data_inheritance.php
#!/usr/bin/php
<?php
class ParentClass{
public static $name = 'Parent class';
}
class ChildClass1 extends ParentClass{
}
class ChildClass2 extends ParentClass{
}
class ChildClass3 extends ChildClass2{
}
function print_name(){
$name1 = ParentClass::$name;
$name2 = ChildClass1::$name;
$name3 = ChildClass2::$name;
$name4 = ChildClass3::$name;
echo "\nParentClass : $name1\n";
echo "ChildClass1 : $name1\n";
echo "ChildClass2 : $name1\n";
echo "ChildClass3 : $name1\n";
}
print_name();
echo "\nUpdating name using ChildClass1\n";
ChildClass1::$name = "Child class1";
print_name();
?>
Output
$./static_data_inheritance.php
ParentClass : Parent class
ChildClass1 : Parent class
ChildClass2 : Parent class
ChildClass3 : Parent class
Updating name using ChildClass1
ParentClass : Child class1
ChildClass1 : Child class1
ChildClass2 : Child class1
ChildClass3 : Child class1
No comments:
Post a Comment