tags:

views:

54

answers:

3

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?

+1  A: 

Make a method in the parent that returns the value, and override it in the child.

class MyClass {

     function getconst() {
          return "yonder";
     }

     public function __construct() {
          echo $this->getconst();
     }
}

class ChildClass extends MyClass {

     function getconst() {
          return "bar";
     }
}
Ignacio Vazquez-Abrams
Wouldn't a function cost more than a constant?
kavoir.com
A: 

I couldn't get it to work with const as it prints "yonderyonder" (that's the thing about constants, they don't change), but it works fine with var:

<?php
class MyClass {

     var $MY_CONST = "yonder";

     public function __construct() {

     echo $this->MY_CONST;
     }
}

class ChildClass extends MyClass {

     var $MY_CONST = "bar";
}

$x = new ChildClass(); // prints 'bar'
$y = new MyClass(); // prints 'yonder'

?>
Cetra
+1  A: 

Instead of

$c = get_class( $this );
echo $c::MY_CONST;

Do this

$c = get_class( $this );
echo constant($c . '::MY_CONST');
Chris