PHP assign object instance to a static property no

2019-03-06 19:40发布

问题:

This question already has an answer here:

  • While making the static class for database getting this error 4 answers

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!

回答1:

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


回答2:

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


回答3:

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


标签: php oop laravel