PHP Call-time pass-by-reference unavoidable?

[亡魂溺海] 提交于 2020-01-11 09:59:15

问题


Given the following interface:

interface ISoapInterface {
  public static function registerSoapTypes( &$wsdl );
  public static function registerSoapOperations( &$server );
}

And the following code:

$soapProvider = array( "FilePool", "UserList" );
foreach( $soapProvider as $provider ) {
  call_user_func( array( $provider, "registerSoapTypes" ), &$server->wsdl );
  call_user_func( array( $provider, "registerSoapOperations" ), &$server );
}

FilePool and UserList both implement ISoapInterface.

PHP will complain about the two calls inside the foreach stating:

Call-time pass-by-reference has been deprecated

So I looked that message up, and the documentation seems quite clear on how to resolve this. Removing the ampersand from the actual call.
So I changed my code to look like this:

$soapProvider = array( "FilePool", "UserList" );
foreach( $soapProvider as $provider ) {
  call_user_func( array( $provider, "registerSoapTypes" ), $server->wsdl );
  call_user_func( array( $provider, "registerSoapOperations" ), $server );
}

Now PHP complains

Parameter 1 to FilePool::registerSoapTypes expected to be reference, value given
Parameter 1 to FilePool::registerSoapOperations expected to be reference, value given

In addition to that, the functionality is now broken. So this obviously can't be the solution.


回答1:


From the call_user_func:

Note that the parameters for call_user_func() are not passed by reference.

To invoke static methods you can use Class::method() syntax, supplying a variable for the Class and/or method parts:

$soapProvider = array( "FilePool", "UserList" );
foreach( $soapProvider as $provider ) {
  $provider::registerSoapTypes($server->wsdl);
  $provider::registerSoapOperations($server);
}



回答2:


While call_user_func does not pass parameters by reference, call_user_func_array can.

$callback = array($provider, 'blahblahblah');
call_user_func_array($callback, array( &$server ));

The only real difference is that it expects an array of parameters instead of a list of parameters like call_user_func (similar to the difference between sprintf and vsprintf)...



来源:https://stackoverflow.com/questions/3968832/php-call-time-pass-by-reference-unavoidable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!