PHP assign object instance to a static property no

2019-03-06 19:23发布

This question already has an answer here:

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?

Error:

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

Code:

class User extends Eloquent{

    public static $user = new Fb();

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

}

Thanks!

标签: php oop laravel
3条回答
可以哭但决不认输i
2楼-- · 2019-03-06 19:47

In addition to another answers,

I'm still new to OOP concepets, what am I doing wrong?

Basically everything. You has both global state and static methods, which is bad. Just using static classes in order to wrap things doesn't mean you use OOP paradigm.

class User extends Eloquent
{
    public static $user = new Fb();

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

}

This is wrong. In terms of OOP, this should be similar to this one:

class User extends Eloquent
{
    private $fb;

    public function __construct(FB $fb)
    {
       $this->fb = $fb;
    }

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

//Usage:

$fb = new FB();
$user = new User($fb);

var_dump($user->mySnippets());
查看更多
姐就是有狂的资本
3楼-- · 2019-03-06 19:49

You can only initialize member variables with basic types.

You'll have to assign to the static variable after the class declaration, or provide a class-level init method or the like which does the assignment.

class User extends Eloquent {
  public static $user = null;

}

User::$user = new Fb();
查看更多
在下西门庆
4楼-- · 2019-03-06 19:55

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).

It could be better like this:

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()
查看更多
登录 后发表回答