用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - asp代码库

PHP 通过$this 传递对象

2014-12-21 作者: asp源码之家举报

[asp]代码库

<!-- 通过$this 传递对象
在这个例子中,我们写一个根据不同的年龄发不同工资的类.
我们设置处理年龄和工资的业务模型为一个独立的类.
-->
<?
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);
        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
$user = new User();
$user->setAge(55);
echo $user->getAge()."age ,his sal is " . $user->getSal();
echo "<br>";
$user->setAge(20);
echo $user->getAge()."age , his sal is " . $user->getSal();
echo "<br>";
$user->setAge(-20);
echo $user->getAge()."age , his sal is " . $user->getSal();
echo "<br>";
$user->setAge(150);
echo $user->getAge()."age , his sal is " . $user->getSal();
?>


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...