R
R
Roman Sokharev2014-08-21 12:25:01
PHP
Roman Sokharev, 2014-08-21 12:25:01

What is the name of such a paradigm/pattern (description inside)?

class SomeClass {
  __call($functionName, $arguments)
  {
    return call_user_func([ self, $functionName . '_' ], $arguments);
  }
  
  __callStatic($functionName, $arguments)
  {
    return call_user_func([ self, $functionName . '_' ], $arguments);
  }
  private function someFunction_(){
    if(empty($this))
    {
      echo 'статичный контекст';
    }
    else
    {
      echo 'объектный контекст';
    }
  }
}
$obj = new SomeClass;
$obj->someFunction();  // 'объектный контекст';
SomeClass::someFunction(); // 'статичный контекст'

The bottom line is that functions are available both in the object and in the static context by the same name / key.
This is because the function "someFunction" does not exist. And therefore, the magic method __call() or __callStatic() is called depending on the context. Next, "_" is added to the function name and the function is called by name.
That's what I'm actually interested in, what is the name of this technique.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Melkij, 2014-08-21
@greabock

I think this pattern is called a "crutch".
Besides, E_STRICT "non-static method SomeClass::someFunction_() should not be called statically" is still there.

class SomeClass {
  public function someFunction(){
    if(empty($this))
    {
      echo 'статичный контекст';
    }
    else
    {
      echo 'объектный контекст';
    }
  }
}
$obj = new SomeClass;
$obj->someFunction();  // 'объектный контекст';
SomeClass::someFunction(); // 'статичный контекст'

The result is the same.

S
Sergey Lerg, 2014-08-21
@Lerg

In general, this is polymorphism.

K
kazin8, 2014-08-21
@kazin8

It's hard to even say what to call this trick...
In fact, it's intercepting a method call and determining the context of this very call
. I don't think it makes sense to come up with a name for such things. In the general case, this is just a part of some pattern (maybe a fluent interface). Try to scroll through the article and read the comments here: habrahabr.ru/post/175935

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question