jamesishereto Posted April 13, 2006 Share Posted April 13, 2006 Hi.I was wondering if there is any way in the given example below for the original display function to still perform the same function but using the redefined constant from the second class? Thanks,James[code]class A {const MYCONST = 'abc';function display() {echo A::MYCONST;}}class B extends A {const MYCONST = 'def';}[/code] Quote Link to comment Share on other sites More sharing options...
toplay Posted April 13, 2006 Share Posted April 13, 2006 The A class is standalone and would know nothing about B's existence. However, the B class can access class A's constant. Example:[code]<?PHP// PHP 5class A { const MYCONST = 'abc'; function display() { echo 'const: ', self::MYCONST, '<br/>'; // displays: abc }}class B extends A { const MYCONST = 'def'; function display() { echo 'self const: ', self::MYCONST, '<br/>'; // displays: def echo 'parent const: ', parent::MYCONST, '<br/>'; // displays: abc }}echo A::MYCONST, '<br/>'; // displays: abcecho A::display(); // displays: abc$a = new A();$a->display(); // displays: abcecho B::MYCONST, '<br/>'; // displays: defecho B::display(); // displays: def and abc$b = new B();$b->display(); // displays: def and abc?>[/code] Quote Link to comment Share on other sites More sharing options...
jamesishereto Posted April 13, 2006 Author Share Posted April 13, 2006 So is there another way to change the output given by the function in A by changing a const or var or something in B?This code gets me what I need but is there a more sensible way to do so?[code]<?phpclass A { protected $value = 'Original'; function display() { echo $this->value; } }class B extends A { protected $value = 'Contemporary'; }$B = new B();$B->display();?>[/code] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.