Ste*_*rig 13 php null pass-by-reference
假设我们有一个类似的方法签名
public static function explodeDn($dn, array &$keys = null, array &$vals = null,
$caseFold = self::ATTR_CASEFOLD_NONE)
Run Code Online (Sandbox Code Playgroud)
我们可以通过以下方式省略所有参数来轻松调用该方法$dn:
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com');
Run Code Online (Sandbox Code Playgroud)
我们也可以用3个参数调用该方法:
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, $v);
Run Code Online (Sandbox Code Playgroud)
并有4个参数:
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, $v,
Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER);
Run Code Online (Sandbox Code Playgroud)
但是为什么不可能使用以下参数组合调用该方法,例如:
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, null,
Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER);
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', null, $v);
Run Code Online (Sandbox Code Playgroud)
传递null给方法和依赖默认值之间有什么区别?这个约束是否写在手册中?它可以被规避吗?
小智 12
如果要显式传递NULL,则必须为by-ref参数创建虚拟变量,而不必在单独的行上创建该变量.您可以直接使用$ dummy = NULL之类的赋值表达式作为函数参数:
function foo (&$ref = NULL) {
if (is_null($ref)) $ref="bar";
echo "$ref\n";
}
foo($dummy = NULL); //this works!
Run Code Online (Sandbox Code Playgroud)
我自己发现了这个,我很震惊o_O!
这是PHP文档所说的:
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee(); // returns "Making a cup of cappuccino."
echo makecoffee(null); // returns "Making a cup of ."
echo makecoffee("espresso"); // returns "Making a cup of espresso."
Run Code Online (Sandbox Code Playgroud)
我原本期望makecoffee(null)回归"制作一杯卡布奇诺咖啡".我使用的一种解决方法是在函数内部检查参数是否为null:
function makecoffee($type = null)
{
if (is_null($type)){
$type = "capuccino";
}
return "Making a cup of $type.\n";
}
Run Code Online (Sandbox Code Playgroud)
现在makecoffee(null)返回"制作一杯卡布奇诺咖啡".
(我意识到这实际上并没有解决与Zend相关的问题,但它可能对某些人有用...)