I saw this example from php.net:
<?php class MyClass { const MY_CONST = "yonder"; public function __construct() { $c = get_class( $this ); echo $c::MY_CONST; } } class ChildClass extends MyClass { const MY_CONST = "bar"; } $x = new ChildClass(); // prints 'bar' $y = new MyClass(); // prints 'yonder' ?>
But $c::MY_CONST is only recognized in version 5.3.0 or later. The class I'm writing may be distributed a lot.
Basically, I have defined a constant in ChildClass and one of the functions in MyClass (father class) needs to use the constant. Any idea?
The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.
You just have to create an object of the child class and call the function of the parent class using dot(.) operator.
Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.
How about using static::MY_CONST
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With