Jump to content

PHP5 OOP Constants + Help Needed


jamesishereto

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.