PHP中__set()和__get()的概念是什么?具体作用(用处)呢?还有$this->name=$name代表了什么意思?
__set()例子<?phpclassemployee{public$name;function__set($propname,$propvalue){$this->$p...
__set()例子
<?php
class employee
{
public $name;
function __set($propname,$propvalue)
{
$this->$propname = $propvalue;
}
}
$employee = new employee();
$employee->name = "mario";
$employee->title = "executive chef";
echo "name:".$employee->name;
echo "<br/>";
echo "title:".$employee->title;
?>
输出:name:mario
title:executive chef,请问EMPLOYEE类中并没有定义TITLE的属性,为何下面可以显示输出title的字符串?
__get()例子
<?
class employee
{
public $name;
public $city;
protected $wage;
function __get($propname)
{
echo "__get called!<br/>";
$vars = array("name","city");
if (in_array($propname,$vars))
{
return $this->$propname;
}else{
return "no such variable";
}
}
}
$cmployee = new employee();
$employee->name = "mario";
echo $employee->name ."<br/>";
echo $employee->wage;
?>
运行输出:mario,但是书本上运行输出mario ,__get called no such variacle,请问我照着书上代码敲的,为何结果不同,是书上错了么?还有就是$this->$propname是什么意思?与上例中$this->$propname = $propvalue;有和不同?
好多疑问,请老师们解答下,不胜感激。。书上的解释看不懂。。 展开
<?php
class employee
{
public $name;
function __set($propname,$propvalue)
{
$this->$propname = $propvalue;
}
}
$employee = new employee();
$employee->name = "mario";
$employee->title = "executive chef";
echo "name:".$employee->name;
echo "<br/>";
echo "title:".$employee->title;
?>
输出:name:mario
title:executive chef,请问EMPLOYEE类中并没有定义TITLE的属性,为何下面可以显示输出title的字符串?
__get()例子
<?
class employee
{
public $name;
public $city;
protected $wage;
function __get($propname)
{
echo "__get called!<br/>";
$vars = array("name","city");
if (in_array($propname,$vars))
{
return $this->$propname;
}else{
return "no such variable";
}
}
}
$cmployee = new employee();
$employee->name = "mario";
echo $employee->name ."<br/>";
echo $employee->wage;
?>
运行输出:mario,但是书本上运行输出mario ,__get called no such variacle,请问我照着书上代码敲的,为何结果不同,是书上错了么?还有就是$this->$propname是什么意思?与上例中$this->$propname = $propvalue;有和不同?
好多疑问,请老师们解答下,不胜感激。。书上的解释看不懂。。 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询