note 102160 deleted from language.oop5.magic by danbrown
| From: | danbrown@php.net | Date: | Mon, 31 Jan 2011 13:44:27 +0000 |
| Subject: | note 102160 deleted from language.oop5.magic by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176532@lists.php.net to get a copy of this message | ||
Note Submitter: mpotra.com
----
Actually, @moechofe, you can use callable members inside another class, by applying the following
technique:
<?php
class CallableClass {
function __invoke( $x ) {
var_dump( $x );
return $this;
}
public function dump( $x ) {
var_dump( $x );
return $this;
}
}
class NoInvoke { // simple class, invoke on member won't work
public $test = NULL;
function __construct() {
$this->test = new CallableClass();
}
}
class YesInvoke { //same class, but with an added method to allow invoke
public $test = NULL;
function __construct() {
$this->test = new CallableClass();
}
public function test( $x ) { // create a method with the same name as the member (in this case:
test )
$p = &$this->test; // store a reference to the member, so we can request its __invoke
ability
return $p( $x ); // return $p( $x ) which equals to $this->test->__invoke( $x )
}
}
$mycall = new CallableClass();
var_dump( $mycall( 7 ) ); //int(7) // object(CallableClass)# (0) {}
var_dump( $mycall->dump( 8 ) ); //int(8) // object(CallableClass)# (0) {}
$noinvoke = new NoInvoke();
//var_dump( $noinvoke->test( 7 ) ); //Fatal error: Call to undefined method NoInvoke::test()
!!!
var_dump( $noinvoke->test->dump( 8 ) ); //int(8) // object(CallableClass)# (0) {}
$yesinvoke = new YesInvoke() ;
var_dump( $yesinvoke->test( 7 ) ); //int(7) // object(CallableClass)# (0) {}
var_dump( $yesinvoke->test->dump( 8 ) ); //int(8) // object(CallableClass)# (0) {}
?>
And in case you don't want to spend time adding functions for each callable object, use __call:
<?php
class YesInvoke2 {
public $test = NULL;
public $dynamic = NULL;
function __construct() {
$this->test = new CallableClass();
$this->dynamic = new CallableClass();
}
function __call( $name, $args ) {
if( is_callable( $this->$name ) ) {
return call_user_func_array( $this->$name, $args );
}
}
}
$yesinvoke2 = new YesInvoke2();
var_dump( $yesinvoke2->test( 7 ) ); //int(7) // object(CallableClass)# (0) {}
var_dump( $yesinvoke2->test->dump( 8 ) ); //int(8) // object(CallableClass)# (0) {}
var_dump( $yesinvoke2->dynamic( 7 ) ); //int(7) // object(CallableClass)# (0) {}
var_dump( $yesinvoke2->dynamic->dump( 8 ) ); //int(8) // object(CallableClass)# (0) {}
?>