<分区>
我正在尝试使用 PHP 5.5.13 通过构造函数初始化一个类,但得到了一些奇怪的结果。设置是这样的:
class foo{
public $bar;
public $top;
public $bot = array();
function __construct($bar, $top){
$this->$bar = $bar;
$this->$top = $top;
}
}
$phonebook = array();
$user_input = $_POST['query'];
if(/* regex match */){
foreach($valid_input[0] as $arr){
$name_and_number = explode(" ", $arr);
$phonebook[] = new foo($name_and_number[0], (int) $name_and_number[1]); //e.g. Bob, 123
var_dump($phonebook[count($phonebook)-1]);
}
}
现在奇怪的是,电话簿的 var_dump 返回:
object(foo)#1 (5) { ["bar"]=> NULL ["top"]=> NULL ["bot"]=> array(0) { }
["Bob"]=> string(3) "Bob" ["123"]=> int(123) }
运行:
echo "$phonebook[0]->$bar";
echo "$phonebook[0]['Bob']"; //Since a Bob field apparently exists?
echo "$phonebook[0]->$Bob"; //Just to test if maybe a $Bob variable has been declared?
全部返回一个空页面。我在这里不知所措。我的构造函数设置很奇怪吗?或者我尝试访问变量的方式?