Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP methods that work in both instantiated and static contexts?
    text
    copied!<p>I'm trying to setup some PHP methods that are callable in instantiated and static contexts. What are some good ways to do this? For example I want to be able to do:</p> <pre><code>Foo::bar($item); foo($item)-&gt;bar(); </code></pre> <p>I could setup two separate classes and have each function modify the thisArg and delegate to the other, but it seems like there's got to be a better way. The only way I could think of to do it with only one class would be something like this:</p> <pre><code>function foo($item = null) { return $item instanceof Foo ? $item : new Foo($item); } class Foo { protected $wrapped; public function __construct($item = null) { $this-&gt;wrapped = $item; } public function get() { return $this-&gt;wrapped; } public function bar($item = null) { isset($this) and $item = &amp;$this-&gt;wrapped; // do stuff with $item return isset($this) ? $this : $item; } } </code></pre> <p>If you look at the code of <a href="https://github.com/brianhaveri/Underscore.php/blob/master/underscore.php" rel="nofollow noreferrer">underscore.php</a> they do something like that. I've read some related <a href="https://stackoverflow.com/questions/2347475/php-issetthis-and-using-the-same-object-method-in-a-static-and-object-context">questions from a while back</a> which point out that using <code>isset($this)</code> to determine the context can raise a warning, but it seems to work fine...any updated thoughts on that? Another possibility is could be to make two classes, one with all static version of the methods and then a second class that uses <a href="http://www.php.net/manual/en/language.oop5.overloading.php#object.call" rel="nofollow noreferrer">__call</a> to delegate to the static method like: </p> <pre><code>class _Foo { protected $wrapped; public function __construct($item = null) { $this-&gt;wrapped = $item; } public function __call($method_name, $args) { array_unshift($args, $this-&gt;wrapped); $this-&gt;wrapped = call_user_func_array('Foo::' . $method_name, $args); return $this; } } </code></pre> <p>Ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload