0

I wanted to create a method in the User model that behaves differently when called statically or non-statically. Basically it should do this:

public function foo() {
    // based on http://stackoverflow.com/questions/3824143/how-can-i-tell-if-a-function-is-being-called-statically-in-php
    if(isset($this) && get_class($this) == __CLASS__) {
        $static = true;
    } else {
        $static = false;
    }
    if($static)
        $user = Auth::user();
    else
        $user = $this;
    // Do stuff with the user
    return $user->bar;
    // ...
}

But it gives me the error: Non-static method User::foo() should not be called statically, assuming $this from incompatible context.

Pedro Moreira
  • 961
  • 1
  • 13
  • 28
  • With a Facade and a Service Provider you can do that. At your vendor dir you may find some examples. Also check this link, http://jasonlewis.me/article/laravel-4-develop-packages-using-the-workbench – user2094178 Apr 14 '14 at 15:38
  • @user2094178 That seems to be a huge lot of work just to do what I want (basically define the object to be used, based on the way the function was called). I was actually expecting that a simple check would be enough, like in my example. – Pedro Moreira Apr 14 '14 at 15:59
  • Yes, although facades and service providers are the laravelish way, but not for models, I overlooked it initially. – user2094178 Apr 14 '14 at 16:23

2 Answers2

1

It is not possible to define the same method twice; statically and non-statically.

However, you could achieve this by using the magic methods __call and __callStatic

class User {
    public function __call($method, $args) {
        if (method_exists($this, 'instance_' . $method)) {
            return call_user_func_array([$this, 'instance_' . $method], $args);
        }
    }

    public static function __callStatic($method, $args) {
        if (method_exists(__CLASS__, 'static_' . $method)) {
            return call_user_func_array([__CLASS__, 'static_' . $method], $args);
        }
    }
}

This would pass calls to $user->fn() and User::fn() to $user->instance_fn() and User::static_fn().

Ronni Egeriis Persson
  • 2,209
  • 1
  • 21
  • 43
0

Basically:

You can call static methods from a non-static method but not vice versa.

So you can also use magic methods like this:

public function __call($method, $args)
{
    return call_user_func(get_class_name($this) .'::'. $method, $args);
}

Like this, you can call every static method with the syntax of a non-static method.

hannesvdvreken
  • 4,858
  • 1
  • 15
  • 17