【问题标题】:Access static variable from within a class从类中访问静态变量
【发布时间】:2014-02-14 02:57:55
【问题描述】:

简单的问题,是否可以通过$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';
}

【问题讨论】:

  • 是的,这是正确的。我想我需要离开电脑一个小时。休息一下:)

标签: php class methods static


【解决方案1】:

您只需像这样访问变量:

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();
    }
}

【讨论】:

  • 哦,是的,呵呵。如果有人问这个问题,我可能会回答。谈论过度思考它。谢谢。
  • 每个人都会遇到这种情况^^
【解决方案2】:

试着理解静态的目的。

静态使它们无需实例化即可访问。

如果静态变量在类中,它们应该如下访问

self::$var1;

在你的情况下是可能的

testA::$var1;

会在这里完成工作。

【讨论】:

  • 谢谢,但self::$var1; 不正确,因为它是在课堂外访问的。不过,当我发表评论时,您更新了答案。 testA::$var1; 可以解决问题。
  • 我已经提到了这两种情况,所以你可以了解一下
  • 是的,我很感激其他有同样问题的人。这只是一个脑死亡的时刻。如前所述。还是给你投了赞成票:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 2015-02-18
  • 2012-09-06
  • 2015-07-22
  • 2012-06-29
  • 2020-01-12
相关资源
最近更新 更多