>让我们说:
class myclass{
protected $info;
protected $owner;
__construct(){
$this->info = 'nothing';
$this->owner = 'nobody';
}
function getProp($string){
return $this->$string;
}
}
但它不起作用,它不可能吗? 它不返回任何内容或显示错误
它工作正常,但您在 __construct
前面缺少函数关键字。 这将输出"无":
<?php
class myclass{
protected $info;
protected $owner;
function __construct(){
$this->info = 'nothing';
$this->owner = 'nobody';
}
function getProp($string){
return $this->$string;
}
}
$test = new myclass();
echo $test->getProp('info');
我在__construct之前添加了function
,但除此之外,它似乎工作正常
class myclass{
protected $info;
protected $owner;
function __construct(){
$this->info = 'nothing';
$this->owner = 'nobody';
}
function getProp($string){
return $this->$string;
}
}
$m = new myclass();
echo $m->getProp('info');
// echos 'nothing'
我认为你应该阅读PHP的神奇方法。你正在做的事情是很有可能的,但你这样做的方式可能不是最好的。
http://php.net/manual/en/language.oop5.magic.php
我认为您应该查看__get()和__set()方法。