Jump to content

Archived

This topic is now archived and is closed to further replies.

jamesishereto

PHP5 OOP Constants + Help Needed

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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 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

?>
[/code]

Share this post


Link to post
Share on other sites
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]
<?php

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

class B extends A {

    protected $value = 'Contemporary';
    
}

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

?>
[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.