【问题标题】:how to use get_class() with scope resolution operator in PHP?如何在 PHP 中使用 get_class() 和范围解析运算符?
【发布时间】:2011-10-07 12:45:44
【问题描述】:
<?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_class() 将始终返回 X。$this 未在静态函数中设置。启用错误并阅读日志以了解。您可能正在寻找 get_called_class()
  • Thanx binaryLV 我已更改变量名。
  • hakre -> get_class() 正在返回类名 Y,请检查自己

标签: php oop


【解决方案1】:

您正在寻找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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 2011-11-04
    • 2021-09-26
    • 2015-11-10
    • 1970-01-01
    • 2013-06-13
    • 2011-07-28
    相关资源
    最近更新 更多