提问人:anche 提问时间:3/13/2015 最后编辑:anche 更新时间:3/13/2015 访问量:297
如何在类变量和函数参数中使用变量变量
How to use variable variables in class variables and function arguments
问:
这就是我想做的:
class Contacts {
private $_plural = 'contacts';
private $_single = 'contact';
private $_factory = 'contactfactory';
private $_model = 'contact_model';
private $_idname = $_plural . "Id";
function a($$_idname = 0) {
}
}
这两行:
private $_idname = $_plural . "Id";
和
function a ($$_idname = 0) {
不工作。为什么?我该如何解决这个问题?
编辑
关于函数参数:
如果 $_idname = “contactId”,我希望参数$contactId。这就是为什么我在那里有两个美元符号。这可能不是处理这个问题的正确方法,但这就是我想完成的。
答:
1赞
StackSlave
3/13/2015
#1
你可以改变
private $_idname = $_plural . "Id";
自
private $_idname;
public function __construct(){
$this->_idname = $this->_plural.'Id';
}
第一。
在 中看得不够多。可能更像是:function a
public function a($really = 'What is the point of those underscores?'){
${$this->_idname} = $really; // local $contacts var holds $really
}
我真的猜测你想要一个可以自动更改实例化 Object 属性的方法。为此,您不需要变量变量。如果要影响作为参数传递的变量,则为 .无需将实例化 Object 的属性传递给它自己的方法,因为您已经可以在 .&$yourVar
$this->yourVar
评论
0赞
anche
3/13/2015
$this->_plural,也不起作用。我收到错误:解析错误:语法错误,关于函数变量的意外“$this”(T_VARIABLE)。我将编辑我的问题
2赞
Diego Bauleo
3/13/2015
#2
根据 PHP 的文档,您必须使用常量值初始化 class 属性:
此声明可以包括初始化,但此初始化必须是一个常量值,也就是说,它必须能够在编译时进行计算,并且不能依赖于运行时信息才能进行计算。
解决此问题的方法是使用类构造函数:
function __construct() {
$this->_idname = $this->_plural . "Id";
}
此外,您不能在函数或方法上使用动态变量名称:
请注意,变量变量不能在函数或类方法中与 PHP 的超全局数组一起使用。变量 $this 也是一个不能动态引用的特殊变量。
评论
0赞
anche
3/13/2015
我确实想过在构造函数中以这种方式进行操作,但我认为在我声明类变量的地方这样做可能会更干净、更清晰。无论如何,感谢您的信息。
评论