免费邮箱 |加入收藏 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > PHP专区 > PHP教程

类与对象

时间:2011-05-16 16:00:42  来源:站内  作者:潘春会


<?php
class Item {
  protected
$name, $price, $qty, $total;

  public function
__construct($iName, $iPrice, $iQty) {
   
$this->name = $iName;
   
$this->price = $iPrice;
   
$this->qty = $iQty;
   
$this->calculate();
  }

  protected function
calculate() {
   
$this->price = number_format($this->price, 2);
   
$this->total = number_format(($this->price * $this->qty), 2);
  }

  public function
__toString() {
    return
"You ordered ($this->qty) '$this->name'" . ($this->qty == 1 ? "" : "s") .
   
" at $$this->price, for a total of: $$this->total.";
  }
}

echo (new
Item("Widget 22", 4.90, 2));
?>

You ordered (2) 'Widget 22's at $4.90, for a total of: $9.80.

By loading class Item (which houses all the improvements we made over the first script) into PHP first, we went from having to write 5 statements in the first script, to writing only 1 statement "echo new Item" in the second.

Jason (08-Jul-2008 01:34)

来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
如何找出DHCP地址池里未使用的IP地址
如何找出DHCP地址池里
国内常用的DNS列表
国内常用的DNS列表
Linux邮件服务器软件比较
Linux邮件服务器软件比
学用纯CSS打造可折叠树状菜单
学用纯CSS打造可折叠树
相关文章
栏目更新
栏目热门