我目前一直试图将PHP和HTML分开。我试图只在我的HTML文件中使用内联PHP。有时我想检查数组中的变量是否在echo
之前设置。
这是对问题的一个小测试:
<?
class test
{
private $args;
public function __construct($args = array())
{
$this->args = $args;
}
public function __get($name)
{
return $this->args[$name];
}
function test_i()
{
echo isset($this->i) ? "yes " : "no ";
}
}
$test = new test(array('i' => 'testing'));
//test i while inside the class using $this (returns no)
$test->test_i();
//test i outside of the class using $test (returns no)
echo isset($test->i) ? "yes " : "no ";
//set i to another variable (returns yes)
$ii = $test->i;
echo isset($ii) ? "yes " : "no ";
//returns testing
echo $test->i;
//prints: no no yes testing
?>
我最终想在HTML文件中做的是:
<?=isset($this->var) ? $this->var : ''?>
每次都会返回''
。如果我之后直接echo $this->var
,它将显示正确的var。
为什么这总是返回假?
它与魔法吸气剂方法有关吗?
是因为i
变量没有像private i;
那样直接设置吗?
更新:它是this question的副本。添加magic isset方法修复它:
public function __isset($name)
{
return $this->args[$name];
}
答案 0 :(得分:0)
这是因为只有在您尝试从类外部访问不存在的属性时才会调用__get
。在类中,它不会自动调用,因为你的类应该知道它自己的属性。