为什么我不能像这样在类属性中赋值?首先是我得到的错误:
解析错误:语法错误,第8行的C:\ wamp \ www \ site \ people.php中出现意外的'$ this'(T_VARIABLE)
代码:
$(document).ready(function () {
$(".nav-basic").hover(function () {
$('ul.menu-applied').slideUp('medium');
$('ul.menu-basic').slideDown('medium');
});
$('ul.menu-basic').bind('mouseleave', function(){
$('ul.menu-basic').slideUp('medium');
});
$(".nav-applied").hover(function () {
$('ul.menu-basic').slideUp('medium');
$('ul.menu-applied').slideDown('medium');
});
$('ul.menu-applied').bind('mouseleave', function(){
$('ul.menu-applied').slideUp('medium');
});
});
答案 0 :(得分:0)
您不能在类属性中设置动态值;他们必须是不变的价值观。你必须在构造函数
中进行这样的赋值// NO
private $person_info = $this->getName . ' ' . $this->getGender . ' and ' . $this->getAge() . '.';
// YES
public function __construct() {
$this->person_info = $this->getName . ' ' . $this->getGender . ' and ' . $this->getAge() . '.';
}
但你真正的意思是这个
// you're calling get methods, not properties
// make sure to use $this->getName(), not $this->getName
public function __construct() {
$this->person_info = $this->getName() . ' ' . $this->getGender() . ' and ' . $this->getAge() . '.';
}
但实际上你的所有代码都不好
// This makes no sense to have as a constant property in a class
private $person = array(
'name' => 'Sarah',
'gender' => 'female',
'age' => 21
);
这个课程对你的目的更有意义
class Person {
// container for your info object
private $info = [];
// make info a parameter for your constructor
public function __construct(array $info = []) {
$this->info = $info;
}
// use PHP magic method __get to fetch values from info array
public function __get(string $attr) {
return array_key_exists($attr, $this->info)
? $this->info[$attr]
: null;
}
// use PHP magic method __set to set values in the info array
public function __set(string $attr, $value) {
$this->info[$attr] = $value;
}
// single method to fetch the entire info object
public function getInfo() {
return $this->info;
}
}
简单。让我们看看它现在如何运作
$p = new Person([
'name' => 'Sarah',
'gender' => 'female',
'age' => 21
]);
echo $p->name, PHP_EOL;
// Sarah
echo $p->gender, PHP_EOL;
// female
echo $p->age, PHP_EOL;
// 21
echo json_encode($p->getInfo()), PHP_EOL;
// {"name":"Sarah","gender":"female","age":21}
因为$info
数组现在是一个参数,所以您可以轻松地使用其他数据创建Person对象
$q = new Person([
'name' => 'Joey',
'gender' => 'male',
'age' => 15
]);
echo $q->name, PHP_EOL;
// Joey
echo $q->gender, PHP_EOL;
// male
echo $q->age, PHP_EOL;
// 15
echo json_encode($q->getInfo()), PHP_EOL;
// {"name":"Joey","gender":"male","age":15}