QeePHP 开源社区 - 引领 PHP 开发新思想、新模式's Archiver

coolcool1265 发表于 2009-3-18 09:34

PHP5面向对象中对$this的一个小疑问

[i=s] 本帖最后由 coolcool1265 于 2009-3-18 09:36 编辑 [/i]

[code]<!-- 通过$this 传递对象,在这个例子中,我们写一个根据不同年龄发不同工资的类。
我们设置处理年龄和工资的业务模型为一个独立的类-->
<?php
class User{
private $age;
private $sal;
private $payoff;
//构造函数中创建Payoff的对象
public function __construct(){
$this->payoff=new Payoff();
}
public function getAge(){
return $this->age;
}
public function setAge($age){
$this->age=$age;
}
public function getSal(){
$this->sal=$this->payoff->figure($this); //这里figure($this)中的$this指的是User类本身,可按照下面的应该是$age,这是为啥?
return $this->sal;
}

}
class Payoff{
public function figure($a){
$sal=0;
$age=$a->getAge();
if($age>80||$age<16){
$sal=0;
}elseif($age>50){
$sal=1000;
}else{
$sal=800;
}
return $sal;
}
}
$user=new User();
$user->setAge(55);
echo $user->getAge()."age,his sal is".$user->getSal();
?>[/code]

coolcool1265 发表于 2009-3-18 09:38

public function getSal(){

$this->sal=$this->payoff->figure($this); //[color=Red]这里figure($this)中的$this指的是User类本身,可按照下面的应该是$age,这是为啥?[/color]

return $this->sal;

}

dualface 发表于 2009-3-18 11:28

figure($this) 调用时,$this 就是 User 对象撒,这个没问题。

下面计算时,是 $age = $a->getAge(),也没问题。

coolcool1265 发表于 2009-3-18 16:41

:lito10 恩 呵呵
明白了~
初学初看的 一开始还疑惑着呢
不过现在明白了
觉得廖总推荐的这本php5面向对象 讲的确实很通俗,举得例子也很好。

页: [1]

Powered by Discuz! Archiver 7.0.0  © 2001-2009 Comsenz Inc.