<?php
class student{
var $name;
var $sex;
var $age;
public function __construct($student=array()) {
foreach ($student as $property=>$value) {
$this->property=$value;
echo $property.':'.$this->property.'<br>';
}
}
function say(){
echo "我的名字叫:".$this->name.",性别:".$this->sex.",年龄:".$this->age.".<br>";
}
}$stu = array('name'=>'小枫','sex'=>'男','年龄'=>21);
$student = new student($stu);
$student->say();
?>
运行结果:
name:小枫
sex:男
年龄:21
我的名字叫:,性别:,年龄:.为什么实例化后,$student的值为空呢?? 我就不懂了
foreach ($student as $property=>$value) {
$this->$property=$value;
echo $property.':'.$this->$property.'<br>';
}
}
class student{
private $_name;
private $_sex;
private $_age;
public function __construct($student=array()) {
foreach ($student as $property=>$value) {
if($property == 'name') {
$this->_name = $value;
} else if($property == 'sex') {
$this->_sex = $value;
} else if($property == '年龄') {
$this->_age = $value;
}
}
}
public function say(){
echo "我的名字叫:".$this->_name.",性别:".$this->_sex.",年龄:".$this->_age.".<br>";
}
}$stu = array('name'=>'小枫','sex'=>'男','年龄'=>21);
$student = new student($stu);
$student->say();
<?php
class student{
private $_name;
private $_sex;
private $_age;
public function __construct($student=array()) {
foreach ($student as $property=>$value) {
$this->property=$value; //这段你都懂的给属性赋值
echo $property.':'.$this->property.'<br>';
if($property == 'name') {
$this->_name = $value; //跟第一个一样给属性赋值
} else if($property == 'sex') {
$this->_sex = $value; //跟第一个一样给属性赋值
} else if($property == '年龄') {
$this->_age = $value; //跟第一个一样给属性赋值
}
}
}
public function say(){
echo "我的名字叫:".$this->_name.",性别:".$this->_sex.",年龄:".$this->_age.".<br>";
}
}$stu = array('name'=>'小枫','sex'=>'男','年龄'=>21);
$student = new student($stu);
$student->say();
?>
其实 foreach ($student as $property=>$value) {
$this->$property=$value;
}
执行结果是:
$this->name='小枫';
$this->name='男';
$this->年龄='21';想让它赋值是吧,可以改两个地方,第一个地方就是
$stu = array('name'=>'小枫','sex'=>'男','age'=>21);又或者把
echo "我的名字叫:".$this->name.",性别:".$this->sex.",年龄:".$this->年龄.".<br>";我们也回答了,居然没给我们分数