【问题标题】:PHP | Access to undeclared static propertyPHP |访问未声明的静态属性
【发布时间】:2017-03-23 06:11:15
【问题描述】:

由于某种原因尝试了几次尝试后,当我尝试在我的班级中制作一个对象时,我得到了错误Access to undeclared static property

我的班级:

final class repo {
    var $b;

    /**
     * @var \Guzzle\Http\Client
     */
    protected $client;

    function repo($myvar)
    {
        static::$b = $myvar;
        $this->client = $b;
    }
}

我在制作一个对象:

$myobj = new repo("test");

【问题讨论】:

  • $b 不是静态的。 $this->b = $myvarpublic static $b;
  • 您必须将 $b 初始化为 public static $b 。除非你不能使用它。
  • var $b;。你想支持php4吗?或者你只是读了很老的教程?

标签: php class static


【解决方案1】:

您应该将 $b 声明为静态变量。

另请注意,作为类名的方法现在已弃用 see the details here

final class repo {
    public static $b;

    /**
     * @var \Guzzle\Http\Client
     */
    protected $client;

    function repo($myvar)
    {
        static::$b = $myvar;
        $this->client = static::$b;
    }
}

【讨论】:

  • 那你为什么把static::$b = $myvar;改成$this->b = $myvar;呢?
  • @Federkun 两者都是一样的,它是类的成员,所以我使用了$this,但我们也可以使用范围解析来实现相同的目的。有什么问题吗?
  • 感谢@Federkun 的解释。我会更新我的答案。
【解决方案2】:

声明 var $b; 是 PHP 4。PHP 5 允许它,它等同于 public $b;

但是,它已被弃用,如果您使用正确的错误报告(开发期间error_reporting(E_ALL);),您会收到有关它的警告。您应该改用 PHP 5 visibility kewords

此外,function repo($myvar) 声明是一种 PHP 4 构造函数样式,也被接受但已弃用。您应该使用 PHP 5 __constructor() 语法。

您以static::$b 访问$b,这与其声明不兼容(正如我上面所说,与public $b 等效)。如果你希望它成为一个类属性(这就是static 所做的),你必须将它声明为一个类属性(即public static $b)。

将所有内容放在一起,编写课程的正确方法是:

final class repo {
    // public static members are global variables; avoid making them public
    /** @var \Guzzle\Http\Client */
    private static $b;

    // since the class is final, "protected" is the same as "private"
    /** @var \Guzzle\Http\Client */
    protected $client;

    // PHP 5 constructor. public to allow the class to be instantiated.
    // $myvar is probably a \Guzzle\Http\Client object
    public __construct(\Guzzle\Http\Client $myvar)
    {
        static::$b = $myvar;
        // $this->b probably works but static::$b is more clear
        // because $b is a class property not an instance property
        $this->client = static::$b;
    }
}

【讨论】:

    【解决方案3】:

    试试这个

    final class repo {
        public $b;
    
        /**
         * @var \Guzzle\Http\Client
         */
        protected $client;
    
        function repo($myvar)
        {
            $this->b = $myvar;
            $this->client = $this->b;
        }
    }
    

    注意:static::/self:: 用于静态函数。

    【讨论】:

      猜你喜欢
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多