PHP将对象实例分配给静态属性不起作用 [英] PHP assign object instance to a static property not working

查看:61
本文介绍了PHP将对象实例分配给静态属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel,并且new关键字出现错误.我还不是OOP概念的新手,我在做什么错了?

I am using Laravel and I get an error with the new keyword. I'm still new to OOP concepets, what am I doing wrong?

错误:

Line 3: syntax error, unexpected 'new' (T_NEW) 

代码:

class User extends Eloquent{

    public static $user = new Fb();

    public function mySnippets(){
        return Snippet::all()->where('author','=',self::$user->getUser());
    }

}

谢谢!

推荐答案

您不能在属性声明中使用new.因此,您将需要在需要时进行设置.因为您可能想从静态上下文中使用它,所以构造函数可能不合适(仅当您在类上使用new且在每个对象中会有不同的Fb实例时,才会调用该构造函数).

You cannot use new in the declaration of attributes. So you will have to set it when you need it. As you might want to use it from static context, the constructor might not be appropriate (it only gets called when you use new on your class and you will have different instances of Fb in each object).

这样可能更好:

public static function getUser() {
   if (self::$user == null) self::$user = new Fb();
   return self::$user;
}

然后总是通过以下方式获取静态属性

And then always retrieve the static attribute via

self::getUser()

这篇关于PHP将对象实例分配给静态属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆