what is the best way (memory safe) to use call_user_func from self instance eg.:
call_user_func(array($this, 'method'));
or by reference, eg.:
call_user_func(array(&$this, 'method'));
PS. i know the best way is $this->method but for framework design pattern reason (Wordpress) i do use call_user_func
If I am aware, it doesn't really matter, because PHP will do the same thing in both cases: will just pass reference to the same object (the object will be not cloned). So for simplicity, I would go without &
Some test:
class test
{
function foo() {
call_user_func([$this, 'bar']);
call_user_func([&$this, 'bar']);
}
private function bar() {
echo spl_object_hash($this), PHP_EOL;
}
}
and outputs:
php > $obj = new test();
php > $obj->foo();
0000000025077e4a0000000075174bd2
0000000025077e4a0000000075174bd2
Related
As I am learning how PHP OOP works, I stumbled upon the following confusion.
class Foo {
static function baz() {
echo 'works';
}
}
# 1
$a = 'Foo';
$a::baz();
# 2
Foo::baz();
PHP manual states that since 5.3.0, it is possible to reference a static class via a string (http://php.net/manual/en/language.oop5.static.php)
What I don't understand is, what is the different between #1 and #2? Aren't they technically the same since both are calling a static function without initiating a class? Where can #1 be applied in practical scenario?
The difference is in a version. Before PHP5.3 you cannot use static methods with variable.
Also, second one 'hide' using of a class. Your IDE could not find class usage.
Also you could use object to call static methods.
class Foo {
static function baz() {
echo 'works';
}
}
eval(
'$a = "Foo";
$a::baz();');
eval(
'$a = new Foo();
$a::baz();');
eval(
'Foo::baz();');
http://3v4l.org/WOK44
ok I do have the code below
<?php
class foo{
public $bar = NULL;
public function boo(){
$this->bar();
}
}
$mee = new foo();
//save a closure function on the property
$mee->bar = function(){
echo 'hahaha';
};
//invoke the closure function by using a class method
$mee->boo();
?>
and you can see it running here http://codepad.org/s1jhi7cv
now what i want here is to store the closure function on the class method.
well closures are possible as i read the documentation about it here http://php.net/manual/en/functions.anonymous.php
is this possible? did i went to something wrong? please correct me
Your example code at codepad.org does not work because codepad.org uses PHP 5.2.5, and closure support was only added in 5.3.
However, your code will also not work in a PHP version that supports closures, although you will get a different error: http://codepad.viper-7.com/Ob0bH5
This is a limitation of PHP at present. $obj->member() looks for a method named member and will not look at properties to see if they are callable. It is, frankly, annoying.
The only way I am aware of to make this work without call_user_func()/call_user_func_array() is:
public function boo() {
$func = $this->bar;
$func();
}
You need to exploit some magic functionality of PHP (__call) to make use of that. Extend from Extendable for example:
class Extendable {
static function import($context) {
$self = new static();
while (is_callable($context)) $context = $context($self);
if (is_array($context) || is_object($context) || is_a($context, 'Traversable')) {
foreach($context as $key => $value)
$self->$key = &$value; # preserve keys if
}
return $self;
}
public function __call($name, $args) {
if (isset($this->$name) && is_callable($this->$name)) {
return call_user_func_array($this->$name, $args);
}
throw new BadFunctionCallException(sprintf('Undefined function %s.', $name));
}
}
And you can do the job. It's not that nice. Background and examples are in one of my blog posts:
PHP: Extending stdClass with Closures (plus Visitor)
You can naturally implement that magic functionality your own, too.
Use call_user_func() function:
<?php
class foo{
public $bar = NULL;
public function boo(){
call_user_func($this->bar);
}
}
$mee = new foo();
//save a closure function on the property
$mee->bar = function(){
echo 'hahaha';
};
//invoke the closure function by using a class method
$mee->boo();
This will display "ahahah"
Hope it helps.
You will not be able to do that.
Take for example this code:
class T {
function foo() {
echo 'T::foo';
}
}
$t = new T;
$t->foo = function() {
echo 'Closure::foo';
};
$t->foo();
It works fine on PHP 5.4.6 and/or PHP 5.3.16, however it will result in T::foo getting printed.
This happens because methods, in PHP, are not modifiable class properties, as they are for example in javascript.
However,
$foo = $t->foo;
$foo();
will print Closure::foo as expected.
PHP is not a prototype based language hence you cannot redefine functions
Use __call to catch all non-defined methods and then look up the closure and invoke it. Take a look at my post on this SitePoint thread.
Starting at php 7, you can put round brackets around the instance and method to call the method like so: ($this->bar)();.
This appears to cause a syntax error on earlier versions however.
I use eval() in my current project like this:
if (class_exists($class_name)) //$class_name depends on user input
eval($class_name.'::MyStaticMethod()');
eval() is executed if and only if class with the name $class_name exists so it's kinda safe, but I still don't think that this is the best solution.
Can I do the same what code above does without eval()?
I have recently answered this question. The last part of my answer perfectly answers this question and is much more useful for future readers than answers provided here. That's why I am answering my own question.
PHP has features that gives possibility to avoid using eval in most cases:
PHP is very dynamic language. It has ability to do following stuff with strings:
Define and/or get variable (supported from PHP 4.3). For example:
$variableName = 'MyVariable';
// Create new variable with the name defined in variable $variableName
${$variableName} = 'MyValue';
//Outputs: string(7) "MyValue"
var_dump($MyVariable);
//Outputs: string(7) "MyValue"
var_dump(${'MyVariable'});
Demo
Call function (supported from PHP 4.3). For example:
// Create function with the name defined in variable $functionName
function MyFunction($argument) {
return 'Argument passed is: '.$argument;
}
$functionName = 'MyFunction';
// Outputs:
// string(48) "Argument passed is: Calling MyFunction directly."
var_dump(MyFunction('Calling MyFunction directly.'));
// Outputs:
// string(51) "Argument passed is: Calling MyFunction with string."
var_dump($functionName('Calling MyFunction with string.'));
Demo
Create instance of class (supported from PHP 5.0). For example:
class MyClass {
public function __construct() {
echo 'Constructing MyClass'."\n";
}
}
$className = 'MyClass';
$objFromString = new $className();
// Outputs: object(MyClass)#1 (0) {}
var_dump($objFromString);
Demo
Call static method (supported from PHP 5.0). For example:
class MyClass {
public static function staticMethod() {
return 'MyClass::staticMethod called';
}
}
$staticMethodName = 'staticMethod';
// Outputs: string(28) "MyClass::staticMethod called"
var_dump(MyClass::$staticMethodName());
Demo
And from PHP 5.3 class name can also be defined by string. Example:
class MyClass {
public static function staticMethod() {
return 'MyClass::staticMethod called';
}
}
$className = 'MyClass';
$staticMethodName = 'staticMethod';
var_dump($className::$staticMethodName());
var_dump($className::staticMethod());
Demo
Call instance method of object (supported from PHP 5.0). For example:
class MyClass {
public function instanceMethod() {
return 'MyClass::instanceMethod called';
}
}
$methodName = 'instanceMethod';
$obj = new MyClass();
// Outputs: string(30) "MyClass::instanceMethod called"
var_dump($obj->$methodName());
Demo
Access static and instance properties of object (supported from PHP 5.0). For example:
class MyClass {
public static $myStaticProperty;
public $myInstanceProperty;
}
$staticPropertyName = 'myStaticProperty';
$instancePropertyName = 'myInstanceProperty';
MyClass::${$staticPropertyName} = 'my static value';
$obj = new MyClass();
$obj->{$instancePropertyName} = 'my instance value';
var_dump(MyClass::${$staticPropertyName});
var_dump($obj->{$instancePropertyName});
Demo
PHP has two functions: call_user_func and call_user_func_array for dynamic function/method calls. Both are perfectly documented so I won't go in details here.
Even if everything above is not enough PHP 5 comes with great Reflection API. Unfortunately, documentation has few examples but reflection is quite large topic to cover here. Basically, It's not a big deal to use reflection after reading how it works.
I'd suggest call_user_func.
An alternative to call_user_func() would be calling it like this:
$class_and_method = 'Class::MyStaticMethod()';
$class_and_method();
yes:
call_user_func(array($class_name, 'MyStaticMethod'));
As of PHP 5.3+,
$class_name::MyStaticMethod();
Adisory:
userinput + eval = security hole;
Also eval is an expensive operation requiring parsing the string into an actionable format (parse tree, abstract syntax tree, etc.) and executing the new found logic.
You don't want to eval every little tidbit of code. Use eval if you have something for it to chew on or rather put that logic somewhere where it's reusable and parametrized such as a function.
Also as of php 5.4
$method = array('class_name', 'method_name');
$method(); // calls class_name::method_name()
Is it possible to add methods to functions?
For example:
<?
function func(){
;
}
//add method
func->test = function(){
;
}
func->test();
func();
I'm coming from a javascript background, and therefore I'm used to 'everything is an object'.
EDIT:
I was just explaining where the misconception may often come from for new phpers. I understand the above code doesn't work.
EDIT 2
Figured it out.
class myfunc_class{
function __invoke(){
//function body
}
function __call($closure, $args)
{
call_user_func_array($this->$closure, $args);
}
}
$func = new myfunc_class;
$func->test = function(){
echo '<br>test<br>';
};
$func->test();
$func();
Even sexier :)
class func{
public $_function;
function __invoke(){
return call_user_func_array($this->_function,func_get_args());
}
function __construct($fun){
$this->_function = $fun;
}
function __call($closure, $args)
{
call_user_func_array($this->$closure, $args);
}
}
$func = new func(function($value){
echo $value;
});
$func->method = function(){
echo '<br>test<br>';
};
$func('someValue');
$func->method();
No.
Not everything is an object in PHP. In fact the only thing that is an object is, well, an object. More specifically, and generally, an instantiation of a class.
Your code converted to PHP
// function_object.php
<?php
class FunctionObject {
public method func() {
// do stuff
}
}
?>
In other code you would use it like this:
<?php
// example.php in same folder as function_object.php
include 'function_object.php';
$FuncObj = new FunctionObject;
$FuncObj->func();
Also: read more about PHP & OOP
No, because an object is a different PHP language construct than a function. Functions do not have properties, but are instead simply execution instructions.
But, if func were instead a pre-defined class, then yes... with a bit of witchcraft, ignoring public outcry, foregoing readability and PHP coding standards, and by using closures with the __call() magic method...
class func
{
function __call($func, $args)
{
return call_user_func_array($this->$func, $args);
}
}
$obj = new func;
$obj->test = function($param1, $param2)
{
return $param1 + $param2;
};
echo $obj->test(1,1);
This won't work as you'd think without __call(), because by $obj->test(1,1), PHP thinks you're trying to call a non-existent method of func when out of object scope. But inside, being that the new "test" property is of a type: closure, the call_user_func_array() just sees the "test" property as just another function, so you can hide this bit of trickery from outside scope.
You would need your function func() to return an object, then you'd be able to do something like: func()->test();
But please note that your way of handling objects is not right in PHP and I suggest that you go read the OO documentations here.
In difference to javacript, in PHP not everything is an object. Therefore you need to differ between function and class.
If you want to create an object, you need to define the class first.
class myClass {
}
You can then add as many functions to the class as you need. But you need to define them first:
class myClass {
function test() {
echo "test!\n";
}
}
When everything is ready, you can bring it to life then:
$class = new myClass;
$class->test();
Checkout the manual for more.
You can't do what you're trying to do, but you can define functions inside of other functions.
This example outputs text:
function a() {
function b() { echo 'Hi'; }
}
a();
b();
Output: HiHi
This example outputs an error:
function a() {
function b() { echo 'Hi'; }
}
b();
Output: ERROR
I am just starting out with PHP, and I am wondering if there is a way to add an anonymous function to a class instance.
For instance, lets say...
class A{
public B;
}
$c = new A();
//This is where I am getting a little confused...
//The following wont work
$c->B = function(){echo('HelloWorld');};
$c->B();
What I am hoping to do is reuse the same spit of code in a great number of different applications, and make it so that I can just 'swap-out' and replace functions in specific instances.
I am using php5.3 (so anonymous functions should work, just not in the way that I am using them).
Thanks so very much for your time!!
-GK
You can use the __call magic function for this job. Not a beauty, but it works..
like this:
class A {
public $B;
public function __call($closure, $args)
{
call_user_func_array($this->$closure, $args);
}
}
$c = new A();
$c->B = function () { echo('HelloWorld'); };
$c->B();
FWIW:
PHP 5.3's treatment of anonymous functions is entertaining. This won't work:
$c->B = function() { echo func_get_arg(0); };
$c->B("This fails :(");
This WILL work:
$c->B = function() { echo func_get_arg(0); };
$hilarious = $c->B;
$hilarious("This works!");
To work around this, you need to use a __call hack like the one provided by Oden.
This behavior may change in the future. The array dereferencing RFC was recently committed to PHP's trunk, and the patch has set off a discussion on function call chaining, the syntax of which may allow what you're trying to do without the __call hack. Unfortunately it's proven difficult in the past to get function call chaining working.
# real ugly, but PoC...
class a {
function __call($f, $x) {
call_user_func_array($this->$f, $x);
}
}
$a = new a;
$a->b = function() { echo "Hello world"; };
$a->b();
Sounds like you are describing a Strategy Pattern or Decorator Pattern - there are other ways to achieve this in way which is more easily communicated with other developers who read your code.
You can do something along these lines (which will also work with callbacks that are not closures):
<?php
class A {
private $fun;
function setFun($fun) {
if (!is_callable($fun))
throw new InvalidArgumentException();
$this->fun = $fun;
}
public function fun() {
call_user_func_array($this->fun, func_get_args());
}
}
$c = new A();
$c->setFun(function($a) { echo('HelloWorld ' . $a);});
$c->fun("here");
which gives HelloWorld here.
That said, you should also consider inheritance or the decorator pattern.
This is not an issue anymore by PHP 7;
// no error
$result = ($this->anonFunc)();
$result = ($this->anonFunc)($arg1, $arg2, ...);
See more about AST.
Rather than hooking a __call magic method into your class, you can instead execute the callable directly using call_user_func.
class A {
public $b;
}
$c = new A();
$c->b = function(){echo('HelloWorld');};
call_user_func($c->b); // HelloWorld
Obviously it would be nice for PHP to provide some syntax to execute this directly.