Take the State of PHP 2026 Survey →

Indirect method call by array variable View as Markdown

Implemented (PHP 5.4)
Authors
Felipe Pena felipe@php.net
Date
2011-06-05
Version
1.0
Source
wiki.php.net/rfc/indirect-method-call-by-array-var

Discussions on the mailing list

No thread found. Threads are linked to an RFC when their first email links to the RFC page, or when the RFC page links to them.

RFC text

Copied from wiki.php.net, last synchronized Oct 13, 2026 11:52 UTC

Introduction

Reading our bug tracker I noticed a good feature request (http://bugs.php.net/bug.php?id=47160) from 2009 which points to an interesting feature that I think makes sense for us, since we are now working with $f() using objects and strings, and the array('class', 'method') is an old known for call_user_func()-like functions.

The array to be a valid callback should be a 2-element array, and it must be for the first element object/string and for the second string only. (just like our zend_is_callable() check and opcodes related to init call)

Example

<?php
 
class Hello {
   public function world($x) {
      echo "Hello, $x\n"; return $this;
   }
}
 
 
$f = array('Hello','world');
var_dump($f('you')); // Hello, you
 
?>

Checking for callback, nowadays already recognizes array('class', 'method') as valid callback, so it will facility the indirect call through a variable:

<?php
 
 
class Hello {
   static public function world($x) {
     echo "Hello, $x\n";
   }
}
 
 
function hello_world($x) {
   echo "Hello, $x\n";
}
 
 
$callbacks = array(
   array('Hello', 'world'),
   function ($x) { echo "Hello, $x\n"; },
   'hello_world'
);
 
 
foreach ($callbacks as $k => $callback) {
   if (is_callable($callback)) {
     $callback($k);
   }
}
 
?>

Output:

Hello, 0
Hello, 1
Hello, 2

Patch

  1. http://felipe.ath.cx/diff/fr47160.diff