简单PHP类,未定义变量?
我正在学习PHP中的类和对象,我真的很困惑。这就是我到目前为止所做的:简单PHP类,未定义变量?,php,Php,我正在学习PHP中的类和对象,我真的很困惑。这就是我到目前为止所做的: <?php class ipInfo { public $test1 = 'test'; } $test = new ipInfo(); echo $test->$test1; ?> 您不能使用$符号访问它们: 尝试: 对象属性不需要第二个$(除非使用变量) 使用$引用变量,然后使用->指定要查看的属性 另一方面,如果有一个值为test1的变量名为$var,则可以执行以下操作: $var='
<?php
class ipInfo {
public $test1 = 'test';
}
$test = new ipInfo();
echo $test->$test1;
?>
您不能使用
$
符号访问它们:
尝试:
对象属性不需要第二个
$
(除非使用变量)
使用$
引用变量,然后使用->
指定要查看的属性
另一方面,如果有一个值为test1
的变量名为$var
,则可以执行以下操作:
$var='test1';
echo $test->$var;
这将与代码解释$var中的值一样有效,并假设您是指该属性。在
->$test1
中丢失$
。由于在
echo $test->test1;
echo $test->test1;
$var='test1';
echo $test->$var;