如何在 class 变量和函数参数中使用可变变量

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) {

不工作。为什么?我该如何解决这个问题?

编辑

关于函数参数:

If $_idname = "contactId" 我希望参数为 $contactId。这就是为什么我在那里有两个美元符号。这可能不是处理此问题的正确方法,但这是我想要完成的。

你可以改变

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
}

我真的猜想您想要一个可以自动更改实例化对象的方法 属性。你不需要一个变量变量。如果你想影响你作为参数传递的变量,它是 &$yourVar。无需将实例化对象的 属性 传递给它自己的方法,因为您已经可以在方法中使用 $this->yourVar.

访问它

根据PHP's documentation,你必须用常量值初始化一个class属性:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

解决此问题的方法是使用 class 构造函数:

function __construct() {
    $this->_idname = $this->_plural . "Id";
}

此外,您不能在函数或方法上使用 dynamic variable 名称:

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.