魔法get方法有问题
问题描述:
I am trying to write my own magic __get method in php. But am getting this error: __get() must take exactly 1 argument. The error is referring to the last line in the function below.
Any idea's?
public function __get()
{
$method = 'get'.ucfirst($name);
if(!method_exists($this, $method))
throw new Exception('Invalid property');
var_dump($method);
return $this->{$method}();
}
我正在尝试在php中编写自己的魔法__get方法。 但是我收到此错误: __get() 必须正好用1个参数。 错误是指下面函数的最后一行。 p>
有什么想法吗? p>
公共函数 __get()
{
$ method ='get'.ucfirst($ name);
if(!method_exists($ this,$ method))
throw new Exception('Invalid property');
var_dump ($ method);
返回$ this-> {$ method}();
}
code> pre>
div>
答
you must specify a parameter that refers to the variable name you are trying to access.
答
Pass in $name
:
public function __get($name)
答
Is this better?
public function __get($name)
{
$method = 'get'.ucfirst($name);
if(!method_exists($this, $method))
throw new Exception('Invalid property');
var_dump($method);
return $this->{$method}();
}
I added the name argument.
答
The magic get function required exactly one argument, like the error said. Please try the following code:
public function __get( $name )
答
one argument is missing in __get($name) function. Which will give you the value of required variable.
public function __get($name) {
...
...
}