简体   繁体   中英

how to access value of parent class constant out side of class using child class

I have two classes
Class a as parent
Class b as child
Class a and class b both have same constant with some values
And i initialize child class b
Now if i want to access value of parent class constant out side of class using child class object $test
How can i do that.
For eg $test::version //output 2.5.0, what i want 2.4.0

<?php
class a{
     const version='2.4.0';
    public function childClassVersion(){
        echo static::version;

    }
   public function parentClassVersion(){
        echo self::version;

    }
}
class b extends a{
         const version='2.5.0';
}
$test=new b;
echo $test::version; // output 2.5.0
echo "<br>";
echo b::version; // output 2.5.0
echo "<br>";
echo a::version; //output 2.4.0
echo "<br>";
$test->childClassVersion(); // output 2.5.0
echo "<br>";
$test->parentClassVersion(); // output 2.4.0
echo "<br>";

I am not certain from the discussion in the comments, but maybe this is what you are looking for:

<?php
class a{
    const version='2.4.0';
    public function childClassVersion(){
        return static::version;
    }
}
class b extends a{
    const version='2.5.0';
    public function parentClassVersion(){
        return parent::version;
    }
}
$test=new b;
var_dump($test::version); // output 2.5.0
var_dump(b::version); // output 2.5.0
var_dump(a::version); //output 2.4.0
var_dump($test->childClassVersion()); // output 2.5.0
var_dump($test->parentClassVersion()); // output 2.4.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM