php - Is there an array-to-callable function? -


setting

within someclass there f2member taking 2 integer arguments , producing sum. test passes showing call actualy works , retrieves expected result. calling $gwith 2 parameters 1 , 1 returning 2.

important: works php 5.4.11 , upwards compatibility check

class someclass extends phpunit_framework_testcase {        function f2member($a,$b)     {         return $a + $b;     }      /**      * @test      */     public function test()     {         $g = array($this,'f2member');         $this->assertequals(2, $g(1,1)); // squiggle line under $g     } } 

problem

however, produces warning inside phpstorm on every method invocation , squiggle line under $g:

squiggle line warning in phpstorm

function name must callable - string, closure or class implementing __invoke, array

the origin of warning clear me , looking ways avoid these warnings. requirement is, dont want change style of calling function. thing don't want deactivate warning. rather prefer wrap around it, provides necessary information type system.

attempt

i encountered several solutions remove warnings. 1 define user defined function, documents required target type.

/**  * @param array $arr  *  * @return callable  */ function callable_for($arr) {     return $arr; } 

this returns array, explicitly tells type system comes out of callable_for function. type annotation in place phpstorm stops complaining warning, although still returns array.

$g = callable_for(array($this,'f2member')); 

question

isn't there out of box callable_for in php achieve this? if answer no, looking concise solution can find.

i tried looking on so, php.net , google. maybe, searched wrong word combinations, here 2 samples:

  • array callable php
  • create callable method handle php

bigpicture

just in case suspects arise x/y problem: have function taking callable parameter. closures natural define something, can invoked later on. however, how define callable member or static method without wrapping in delegation closure? array notation allows used uniformly pass: closures or static/member method handles later function. trying find concise solution this, comes close this.

thus, advancement be, modify callable_for take 2 arguments , wrap both responsibilities; create array , document target return type.

/**  * @param mixed $context  * @param string $method  *  * @return callable  */ function callable_for($context, $method) {     return array($context, $method); } 

using implementation raises conciseness of $g's declaration acceptable level.

$g = callable_for($this,'f2member'); 

this function still returns array, type system can use given information correctly treat array dynamic method invocation.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -