Jump to content


Photo

PHP5 OOP Constants + Help Needed


  • Please log in to reply
2 replies to this topic

#1 jamesishereto

jamesishereto
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 13 April 2006 - 03:50 AM

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



class A {

const MYCONST = 'abc';

function display() {
echo A::MYCONST;
}

}

class B extends A {

const MYCONST = 'def';

}



#2 toplay

toplay
  • Staff Alumni
  • Advanced Member
  • 973 posts

Posted 13 April 2006 - 05:44 AM

The A class is standalone and would know nothing about B's existence. However, the B class can access class A's constant. Example:
<?PHP

// PHP 5

class 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: abc

echo A::display(); // displays: abc

$a = new A();

$a->display(); // displays: abc


echo B::MYCONST, '<br/>'; // displays: def

echo B::display(); // displays: def and abc

$b = new B();

$b->display();  // displays: def and abc

?>


#3 jamesishereto

jamesishereto
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 13 April 2006 - 08:53 AM

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?

<?php

class A {
    
    protected $value = 'Original';
    
    function display() {
    
        echo $this->value;
            
    }
        
}

class B extends A {

    protected $value = 'Contemporary';
    
}

$B = new B();
$B->display();

?>





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users