Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从类中访问静态变量_Php_Class_Methods_Static - Fatal编程技术网

Php 从类中访问静态变量

Php 从类中访问静态变量,php,class,methods,static,Php,Class,Methods,Static,简单的问题是,是否可以从$this->调用访问静态变量 class testA { public static $var1 = "random string"; // current solution public function getVar() { return self::$var1; } } class testB { private $myObject; public function __construc

简单的问题是,是否可以从
$this->
调用访问静态变量

class testA
{
    public static $var1 = "random string";

    // current solution
    public function getVar()
    {
        return self::$var1;
    }
}

class testB
{
    private $myObject;

    public function __construct() {
        $this->myObject = new testA();

        // This line is the question
        echo $this->myObject::var1;

        // current solution
        echo $this->myObject->getVar();
    }
}
恐怕我已经回答了我自己的问题。但是有几个静态变量,我不希望每个变量都有一个函数,甚至当我可以直接访问它时,也不希望只有一个
getVar($staticVar)

如果这是唯一的解决办法。关于如何更好地实施这一点的任何建议

如果我需要为每个函数调用一个函数,那么我最好完全去掉静态变量

//method
public function staticVar1() {
    return (string) 'random string';
}

您只需按如下方式访问变量:

testA::$var1;
因此,使用您的示例,它将是

class testB
{
    private $myObject;

    public function __construct() {
        $this->myObject = new testA();

        // This line is the question
        echo testA::$var1;

        // current solution
        echo $this->myObject->getVar();
    }
}

试着理解静态的目的

静态使它们可以访问,而不需要类的实例化

如果静态变量在类中,则应按如下方式访问它们

self::$var1;
在你的情况下,下面是可能的

testA::$var1;

我会在这里工作。

哦,是的,是的。如果有人问这个问题,我可能会回答。谈论过多的思考。谢谢。每个人都会这样^^谢谢,但是
self::$var1不正确,因为它是在类之外访问的。你在我评论的时候更新了你的答案<代码>测试::$var1