Binyuan Sun
Binyuan Sun

Reputation: 146

Laravel like model

I'm trying to make a Eloquence like model. The Eloquence class's functions are all static but they are using a non-static $table as variable to indicate the model's class. How is that possible to use a non-static variable in a static function?

Edit 1: So if I understand well, the functions are actually non-static but a another function is creating a new static instance of that non-static function. So now I would like to know how to do it without using laravel?

Upvotes: 0

Views: 316

Answers (2)

Endel Dreyer
Endel Dreyer

Reputation: 1654

Under the hood, Eloquent proxies class methods to instance methods.

Example:

class Model {
    public static function __callStatic($method, $arguments) 
    {
        // create an instance of this model
        $instance = new static; 

        // dynamically call instance method, with the same arguments
        return call_user_func_array(array($instance, $method), $arguments);
    }
}

Take a look at real Eloquent\Model implementation.

Upvotes: 1

The Alpha
The Alpha

Reputation: 146191

You said The Eloquence class's functions are all static but it's not true. Instead it uses a static style method calls and it's been possible because of Laravel's Facade classes.

Taken From Laravel's Documentation:

Facades provide a "static" interface to classes that are available in the application's IoC container. Laravel ships with many facades, and you have probably been using them without even knowing it! Laravel "facades" serve as "static proxies" to underlying classes in the IoC container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

Your asked How is that possible to use a non-static variable in a static function? Hope you got the answer. To get more clear idea, read the explanation on Laravel's website.

Upvotes: 0

Related Questions