Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access constant defined in child class from parent class functions?

Tags:

oop

php

class

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?

like image 804
datasn.io Avatar asked Mar 12 '10 03:03

datasn.io


People also ask

Can parent class access child variables?

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.

How do you call the function of parent class in child class?

You just have to create an object of the child class and call the function of the parent class using dot(.) operator.

Does the parent class inherit the child's class properties Why?

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.


1 Answers

How about using static::MY_CONST?

like image 79
pevik Avatar answered Sep 17 '22 19:09

pevik