Help with $ this and self in php [closed]

-1
abstract class BaseModel {
    public function find($params){
        $table = $this->$table;

        //...
    }
}

class User extends BaseModel {
    protected $table = "users";
}

If I do:

$u = new User();
$u->find([]);

It works just because I created a new instance of the user class. but if I want to do it directly:

User::find([]);

I do not get why not to any reference to $this

How do I resolve this?

    
asked by anonymous 09.04.2016 / 04:51

2 answers

2

You can solve this by simply keeping it as you already do

$u = new User();
$u->find([]);

$this can not be statically accessed. So it will not work to User::find([]);

You can do what you want, but not recommended.

If the purpose is merely visual, to have a smaller code, forget it. Or if you want to provide inline access, you can think of something else as method chaining or simply create a function:

function userFinD()
{
    $u = new User();
    return $u->find([]);
}

userFinD();

But if you get annoyed at having to create a function, you can also invoke inline a multi-line routine. For this you use anonymous functions .

As I'm not sure what you're really going to do, I'll avoid detailing the options above.

    
09.04.2016 / 08:56
-2

SOLUTION:

abstract class BaseModel {
    public function find($params){
        $table = '';

        if($this)
            $table = $this->$table;
        else {
            $u = new User();
            $table = $u->table;
            unset($u);
        }

        //...
    }
}

class User extends BaseModel {
    protected $table = "users";
}
    
09.04.2016 / 06:48