繁体   English   中英

如何在 PHP 中将 get_class() 与 scope 分辨率运算符一起使用?

[英]how to use get_class() with scope resolution operator in PHP?

<?php
class X {
    function foo() {

        echo "Class Name:".get_class($this)."<br>"; //it displays Y... :)
        echo get_class($this)::$public_var; //not working
        echo Y::$public_var; //works
        Y::y_method();  //works
        get_class($this)::y_method(); //not working

        $classname = get_class($this);
        $classname::y_method(); // again not working..  :( 
    }

    function bar() {
        $this->foo();
    }
}

class Y extends X {

    public static $public_var = "Variable of Y Class";
    public function y_method()
    {
        echo "Y class method";
    }
}

$y = new Y();
$y->bar();

?>
my only question is how to get access members of y class only with dynamically providing class name without changing current structure.

您正在寻找get_called_class()

class X {
    function foo() {
    $that = get_called_class();
        echo $that::$private_var;
        echo $that::y_method();
    }

    function bar() {
        $this->foo();
    }
}

class Y extends X {

    public static $private_var = "Variable of Y Class";
    public function y_method()
    {
        echo "Y class method";
    }
}

$y = new Y();
$y->bar();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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