rfc:consistent_callables

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
rfc:consistent_callables [2015/09/30 00:30] – Added note about direct invocation not being affected. danackrfc:consistent_callables [2018/08/07 10:58] danack
Line 1: Line 1:
 ====== PHP RFC: Consistent Callables ====== ====== PHP RFC: Consistent Callables ======
-  * Version: 0.1 +  * Version: 0.9 
-  * Date: 2015-09-28 +  * Date: 2017-05-28 
   * Author: Dan Ackroyd   * Author: Dan Ackroyd
-  * Status: Draft +  * Status: Under Discussion 
   * First Published at: https://wiki.php.net/rfc/consistent_callables   * First Published at: https://wiki.php.net/rfc/consistent_callables
  
Line 215: Line 215:
 The following would be the complete list of valid values for the callable type: The following would be the complete list of valid values for the callable type:
  
-i. A string that is the name of a function. +  - A string that is the name of a function
 +  - An array consisting of two elements; a string at index 0 which is a valid fully qualified class name, and a string at index 1 which must meet the conditions: 
 +    * either be the name of a public static function of the class or the class must have a magic %%__callStatic%% method. 
 +    * the name must not be that of an instance method. 
 +  - An array consisting of two elements; an object at index 0, and a string at index 1 where either the string is the name of a public method of the object, or the object has a magic %%__call%% method. 
 +  - An instance of a class (an object) where the class has a public __invoke() method. 
 +  - Closures, which includes anonymous functions.
  
-ii. An array consisting of two elements; a string at index 0, and a string at index 1, where the first string is a valid class name, and the second string is the name of a public static function of the class. 
  
-iii. An array consisting of two elements; an object at index 0, and a string at index 1 where the string is a valid name of a public method of the object. +==== Note - removal of colon separated string ====
- +
-iv. An instance of a class (an object) where the class has a public __invoke() method. +
- +
-v. Closures, which includes anonymous functions. +
- +
- +
-=== Note - removal of colon separated string ===+
  
 This removes the ability to define a callable as a single string composing a class-name and a method name separated by double-colons. The reasons for this are that: This removes the ability to define a callable as a single string composing a class-name and a method name separated by double-colons. The reasons for this are that:
  
-* It is duplication of ii. The duplication of code is not just in PHP core, but for all userland code and libraries that analyze callables must duplicate the handling.+  * It is duplication of ii. The duplication of code is not just in PHP core, but for all userland code and libraries that analyze callables must duplicate the handling.
  
-* For things like routing libraries it is useful for users to be able to specify not a valid callable, but instead a class that needs to be instantiated and the method that should be called on the instantiated object. Having 'classname::methodname' also be a valid callable makes this ambiguous as to whether the user meant to specify a static method of the class, or an instance method.+  * For things like routing libraries it is useful for users to be able to specify not a valid callable, but instead a class that needs to be instantiated and the method that should be called on the instantiated object. Having 'classname::methodname' also be a valid callable makes this ambiguous as to whether the user meant to specify a static method of the class, or an instance method.
  
-* It was introduced without much discussion to address a problem in the SPL iterator. +  * It was introduced without much discussion to address a problem in the SPL iterator. 
 https://github.com/php/php-src/commit/071eaf857633f36fb2b8748b3b08b3cac41f05bc There is no fundamental need for it in PHP. https://github.com/php/php-src/commit/071eaf857633f36fb2b8748b3b08b3cac41f05bc There is no fundamental need for it in PHP.
  
-* It is easier (in the sense of fewer CPU operations) to validate ['className', 'methodName'] as a valid callable than it is to validate 'className::methodName'. Currently each place inside the engine that requires to validate something like 'className::methodName' as a valid callable needs to i) Search for '::', ii) Check that the '::' isn't at the start of a string iii) allocate a string each to hold the classname and method name. By holding the className and methodName separately, those steps can be skipped, as the className and methodName can be used directly.+  * It is easier (in the sense of fewer CPU operations) to validate ['className', 'methodName'] as a valid callable than it is to validate 'className::methodName'. Currently each place inside the engine that requires to validate something like 'className::methodName' as a valid callable needs to i) Search for '::', ii) Check that the '::' isn't at the start of a string iii) allocate a string each to hold the classname and method name. By holding the className and methodName separately, those steps can be skipped, as the className and methodName can be used directly.
  
  
-=== Note - Does not affect calling private/protected methods in correct scope ===+==== Note - Does not affect calling private/protected methods in correct scope ====
  
 While they would no longer pass the type checker for the callable type, private and protected methods could still be executed through call_user_func and direct invocation. While they would no longer pass the type checker for the callable type, private and protected methods could still be executed through call_user_func and direct invocation.
Line 260: Line 258:
 </code> </code>
  
 +In this example, although `$fn` is not a callable that can be passed around to arbitrary scopes, it is valid to call it in the scope that it's in. call_user_func and $fn() will continue to check whether the variable passed in is callable in the current scope. i.e. with is_callable($fn, $syntaxOnly = false, $currentScope = true)
  
-==== Add Scope Resolution Operator for self and parent ==== 
  
-To allow users to resolve class-names in the compile stage of running a PHP script, the scope resolution operator will support `self` and `parent`. 
  
-self::class - represents the current class name. Gives a compilation error if used outside of either class or abstract class context.+==== The strings 'self', 'parent', and 'static' are no longer usable as part of a string callable ====
  
-* parent::class - represent the class-name of the immediate parent of the current class. Gives a compilation error if used outside of a class or abstract context, or if the current class does not have a parent class.+Currently in PHP a callable can be defined using one of these words in place of a classname in a colon separated string like "self::methodName". When something tries to either call that callable, or check if it is callable with is_callable(), the keyword is replaced with the class name depending on the scope that is active. That means that the real value of the callable depends on where it is called from.
  
-Question are there any other cases where it should be allowed or forbidden?+By replacing the run time evaluation of these with the compile time scope resolution, the variable meaning of the values is removed and replaced with a consistent meaning.
  
-<code php> +To be clear, self::class, parent::class and static::class will still be used as part of array based callable e.g. [self::class, 'foo'] or if we keep string based static class method callables `self::class . "::foo"
-class Foo {+
  
-    function getCallback() { 
-        return [self::class, 'fooCallback']; 
-    } 
  
-    public static function fooCallback() +==== Add a is_callable_type() function ====
-     +
-    } +
-}+
  
-class SubFoo extends Foo { +A previous version of the RFC proposed modifying the parameters and meaning of the is_callable() function. This RFC now proposes leaving that function alone(, except for making it more accurately report whether something is callable), and instead adding a separate function to determine if a parameter can be passed as a callable type.
-    function getCallback() +
-        return [parent::class'fooCallback']; +
-    } +
-}+
  
-$foo = new Foo(); +To be clear the meaning of the two functions will be:
-$subFoo = new SubFoo(); +
-$fn1 = $foo->getCallback(); +
-$fn2 = $subFoo->getCallback();+
  
-//$fn1 and $fn2 will callables that have the same value+is_callable() - returns true if a the first parameter is callable in the current scope.
  
-</code>+is_callable_type(mixed $var) : bool - returns true if the parameter can be passed as a callable type, and is callable in any scope, otherwise returns false.
  
 +<code php>
  
 +class Foo {
 + 
 +    private function bar() {}
 + 
 +    public function test($param) {
 +        var_dump(is_callable($param));
 +        var_dump(is_callable_type($param));
 +    }
 +}
 + 
 +$foo = new Foo();
 +$param = [$foo, 'bar'];
 +var_dump(is_callable($param));
 +$foo->test($param);
  
-==== The strings 'self', 'parent', and 'static' are no longer expanded when calling is_callable or other places ====+output will be:
  
-Currently in PHP a callable can be defined using one of these keyword in place of a classname in a colon separated string like "self::methodName". Those keywords are expanded to the full class-name at the time that the callable is called. This means that the real value of the callable depends on where it is called from+false // as the private method cannot be called from the global scope 
- +true  // as the private method can be called from within the class scope 
-By replacing the run time evaluation of these with the compile time scope resolution, the variable meaning of the values is removed and replaced with a consistent meaning.+false // as the private method cannot be passed as a parameter with callable type 
  
 +</code>
  
-## Instance methods are no longer reported as callable for class names:+==== Instance methods are no longer reported as callable for class names ====
  
 <code php> <code php>
Line 332: Line 331:
 </code> </code>
  
-==== Private and protected functions no longer report as callable for is_callable ==== 
  
-As they are not callable from all scopes, private and protected functions will not be valid methods for the is_callable test, or pass as acceptable for functions that have a parameter that has a callable type.+==== Any additional is_callable cleanup ====
  
-It is currently possible using the reflection methods to generate a closure of the private method to allow it to be returned as a calalble. If the 'callable' RFC passes and is added to PHP, it will be possible to use a nicer syntax.+Any other errors in is_callable() will be fixed so that if is_callable($fn) returns true, trying to invoke the function directly or through call_user_func() will not fail due to the callable not being actually callable.
  
 <code php> <code php>
-class Foo { +if (is_callable($fn) === true) { 
- +    $fn();  
-    //This generates a closure to the private method with ugly syntax. +    call_user_func($fn); 
-    public function getCallbackWithCurrentReflection() { +    // given a zero argument, both of these will be guaranteed to work.
-        $reflection = new ReflectionMethod($this, 'somePrivateMethod');         +
-        $callback = $reflection->getClosure($this)+
- +
-        return $callback; +
-    } +
-     +
-    //This will generate a closure to the private method if the 'callable' +
-    //RFC passes +
-    public function getCallbackWithCallableRFC() { +
-        $callback = callable($this, 'somePrivateMethod'); +
- +
-        return $callback; +
-    } +
-     +
-    private function somePrivateMethod() { +
-        echo "This is private."; +
-    }+
 } }
- 
-$foo = new Foo(); 
-$callback = $foo->getCallback(); 
-$callback(); 
 </code> </code>
- 
-This will allow a class to return a private method bound to an instance as a callback, without having to have the private method be exposed to the public API of the class. 
- 
- 
-==== is_callable function change ==== 
- 
-Currently the function is_callable has the signature: 
- 
-<code php> 
-bool is_callable ( callable $name [, bool $syntax_only = false [, string &$callable_name ]] ) 
-</code> 
- 
-which allows users to do this: 
- 
-<code php> 
-class Foo { 
-    function bar() { 
- 
-    } 
-} 
- 
- 
-$obj = new Foo(); 
-is_callable([$obj, "bar"], true, $name); 
-echo $name; //output is Foo::bar 
-</code> 
- 
-The signature will be changed to be: 
- 
-<code php> 
-bool is_callable ( callable $name [, bool $syntax_only = false [, bool $current_scope = false]]) 
-</code> 
- 
-The `$current_scope` flag will allow users to test whether a parameter is actually invokable in the current scope, even if it is not a parameter that is universally callable. e.g. for private functions. 
- 
-<code php> 
-class Foo { 
- 
-    private function bar() {} 
- 
-    public function test($param) { 
-        var_dump(is_callable($param)); 
-        $syntaxOnly = false; 
-        var_dump(is_callable($param, $syntaxOnly, true)); 
-    } 
-} 
- 
-$foo = new Foo(); 
-$param = [$foo, 'bar']; 
- 
-$foo->test($param); 
-//output will be: 
-//false 
-//true 
- 
-</code> 
- 
- 
-To allow detection of code that uses the 3rd parameter to indicate the callable_name should be set, in the last PHP 7.x release we can deprecate (with a warning notice) that using the 3rd parameter is going to be removed in PHP 8.  
  
  
Line 436: Line 354:
 The various things that need to be done to implement this RFC do not need to be all in the same release. There are advantages to having the changes implemented in separate versions. Below is this list of all the changes needed and the target version for them. The various things that need to be done to implement this RFC do not need to be all in the same release. There are advantages to having the changes implemented in separate versions. Below is this list of all the changes needed and the target version for them.
  
-==== Add Scope Resolution Operator for self and parent - 7.1==== +==== Soft-deprecate colon separated string callables - 7.====
- +
-This is a useful thing to have (in a small set of circumstances) and there is no reason not to introduce it sooner rather than late. It will allow people to start migrating any code that currently uses "parent::methodName" to [parent::class, "methodName"+
- +
- +
-==== Soft-deprecate colon separated string callables - 7.====+
  
 Soft-deprecate colon separated string callables (i.e. things like "classname::methodname"). Soft-deprecate means write in the manual that it will be removed at some future point. No deprecation notices are shown in code and so there is no difference in code. The only thing that this is for is to allow people to know that this will be removed at some point in the future. Soft-deprecate colon separated string callables (i.e. things like "classname::methodname"). Soft-deprecate means write in the manual that it will be removed at some future point. No deprecation notices are shown in code and so there is no difference in code. The only thing that this is for is to allow people to know that this will be removed at some point in the future.
Line 459: Line 372:
 ==== Remove support for "self::methodname" and "parent::methodname"  - 8 ==== ==== Remove support for "self::methodname" and "parent::methodname"  - 8 ====
  
-Although this is covered by "Remove colon separated string callables"am listed this as a separate task for clarity. +Although this is covered by "Remove colon separated string callables"have listed this as a separate task for clarity. 
  
 ==== Change behaviour of is_callable - 8 ==== ==== Change behaviour of is_callable - 8 ====
Line 469: Line 382:
 Change the behaviour to reflect the new set of things that are listed as callable above. This is a non-trivial change, and although it would be nice to have it sooner than PHP 8, I can't see any acceptable way to do it without making people angry. Change the behaviour to reflect the new set of things that are listed as callable above. This is a non-trivial change, and although it would be nice to have it sooner than PHP 8, I can't see any acceptable way to do it without making people angry.
  
-==== Change function signature of is_callable - 8 ==== 
  
-A comment has been made that changing the signature of this function could be a hard to manage BC break. The position of this RFC is that changing the signature at a major release shouldn't be a big problem as: 
  
-* no PHP programmer I have spoken to is even aware this function takes 3 parameters.+===== BC breaks =====
  
-* I have not been able to find any code that uses the 3rd parameter.+All of the BC breaks are targeted at the PHP 8 release. None of the other changes should have any BC impact, other than the deprecated notices, which will allow people to migrate their code easily.
  
-* As we are deprecating all code that uses callables like "self::methodName" before PHP 8and have provided alternative functionaltiy (self::class and parent::class) it shouldn'be a problem for people to migrate.+1. Any usage of the double-colon separated string as a callablewould need to be changed to an array.
  
-===== BC breaks =====+2. Although there are semantic changes to exactly what is a callable, I don't believe these would be that impactful, as the new semantics more closely reflect how people actual use callables. e.g. having a private method report as callable outside of the class where it is defined is just currently not a useful thing, and so I don't think many people will be dependent on that behaviour.
  
-All of the BC breaks are targetted at the PHP 8 release. None of the other changes should have any BC impactother than the deprecated notices, which will allow people to migrate their code easily.+3. There may be code in the wild that relies on the dynamic meaning of 'self::someMethod'. This code would need to be re-written with the dynamic resolution of method done in userlandas the dynamic resolution would no longer be done by the engine.
  
-1. Any calls to is_callable that use the `callable_name` parameter would at least need to be wrapped in a version check against the PHP_MAJOR_VERSION number. I believe the amount of code that uses this parameter is minimal.  
  
-2. Any usage of the double-colon separated string as a callable, would need to be changed to an array.+===== Implementation ===== 
  
-3Although there are semantic changes to exactly what is callableI don't believe these would be that impactful, as the new semantics more closely reflect how people actual use callables. e.ghaving a private method report as callable outside of the class where it is defined is just currently not a useful thing, and so I don't think many people will be dependent on that behaviour.+None yetThis could be large amount of workso it is appropriate to get feed back on the mailing list before starting this workThe actual change of definition of callable would be a relatively small amount of work. However the SPL libraries make use of colon separated strings (including "self::methodName"and it will be a non-trivial task to go through all that code.
  
-4. There may be code in the wild that relies on the dynamic meaning of 'self::someMethod'. This code would need to be re-written with the dynamic resolution of method done in userland, as the dynamic resolution would no longer be done by the engine. 
  
 +===== TODO =====
  
-===== Implementation ===== +Investigate weird stuff like:
  
-None yet. This could be a large amount of work, so it is appropriate to get feed back on the mailing list before starting this work. The actual change of definition of callable would be a relatively small amount of work. However the SPL libraries make use of colon separated strings (including "self::methodName"and it will be a non-trivial task to go through all that code.+$callable = [FooParent::class, 'parent::bar']; 
 + 
 +assert(\is_callable($callable)); 
 +https://bugs.php.net/bug.php?id=75853&edit=3
rfc/consistent_callables.txt · Last modified: 2021/10/20 13:18 by danack