默认情况下PHP函数的参数作为T_VARIABLE? [英] PHP default function argument as a T_VARIABLE?
问题描述
我想提供一个成员变量为一个类方法的默认值。
I'm trying to provide a member variable as a default value for a class method.
我知道这是不可能使用一个变量作为一个非类函数的默认值,但是看起来应该有办法在类中做到这一点。
I know it's impossible to use a variable as a default value for a non-class function, but it seems like there should be a way to do this within a class.
必须有办法做到这一点 - 也许我只是有错误的语法:
There must be a way to do it - perhaps I just have the wrong syntax:
class test{
private $test = '';
__construct(){
$this->test = "whatever";
}
function getTest($var = $this->test){
echo $var;
}
}
但是,这将引发一个错误,说是这样的:
but this throws an error saying something like:
$这个 - >测试作为函数参数的默认值是不允许的。意外T_VARIABLE。
$this->test as a function argument default value is not allowed. unexpected T_VARIABLE.
有什么想法?
推荐答案
从<一个href=\"http://www.php.net/manual/en/functions.arguments.php#functions.arguments.default\">manual:-
默认值必须是常量
前pression,而不是(例如)
变量,类成员,或者函数
呼叫。
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
我可能只是做一些事情,如: -
I'd probably just do something like:-
<?php
class Test {
public function __construct() {
$this->test = "whatever";
}
public function getTest($var=NULL) {
if (is_null($var)) {
$var = $this->test;
}
echo $var;
}
}
?>
这篇关于默认情况下PHP函数的参数作为T_VARIABLE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!