php中的属性,PHP中属性和方法的定义

PHP中属性和方法的定义

属性的定义方法:

Var variable_name;

Var是关键字,variable_name是要定义的属性名。

注意:PHP类的方法也是这样定义的。

例如:

Class php

{

Var $phpdo;

Function fun($phpdo)

{

$phpdo = “This is www,phpdo.net !”;

$this->a = $phpdo;

}

}

用PHP编程,在类中定义的函数与类同名时,这个函数将会被PHP认为是构造函数。当创建一个类的实例时,将会自动调用构造函数。

构造函数主要有以下特点:

构造函数的函数名和类名必须完全相同;

构造函数没有返回类型和返回值;

构造函数的主要功能是对类中的对象初始化。

注意:构造函数既可以为有参函数,也可以为无参函数。

构造函数__construct

功能:可以创建函数的构造函数

例如:

class Php

{

function __ construct() //构造函数

{

print “This is www.phpdo.net”;

}

}

$myclass = new Php;

?>

结果:This is www.phpdo.net

注意:__construct前面的下斜线为两个“_”

析构函数__destruct

功能:析构函数可以销毁对象。

例如:

class Php

{

function __destruct() //析构函数

{

print “This is www.phpdo.net!”;

}

}

$MyClass = new Php;

$MyClass = null;

?>

结果:This is www.phpdo.net!

字符串转换函数__toString

功能:因为print和echo输出数据类型为对象的数据,所以就有了__toString

例如:

class Myclass

{

var $name;

function __construct($name)

{

$this->name = $name;

}

}

$myclass = new Myclass(“Simon”);

echo $myclass;

?>

使用__toString之后呢?

例如:

class Php

{

var $name;

function __construct($name)

{

$this->name = $name;

}

function __toString()

{

return $this->name;

}

}

$myclass = new Php(“Simon”);

echo $myclass;

?>

结果:Simon

<?php /**  * 这个类的一个对象实例表示一个购物车对象,表模型里面也可以写方法  * Enter description here ...  * @author harry_manage_top_100  *  */ class  MyCart extends  Zend_Db_Table{     protected   $_primary='id';  protected  $_name='mycart';    var  $total_price=0;    //添加商品到购物车(把登录用户选中的商品保存到mycart表中)  function addProduct($userId,$productId,$nums=1){    $res=$this->fetchAll("userid=$userId  AND  bookid=$productId")->toArray();    if(count($res)>0){    //说明该用户的购物车记录中,已经购买过这个商品,因此这里我们需要更新数量就可以了。    $old_nums=$res[0]['nums'];    $data=array(       'nums'=> $old_nums+1     );    $where="userid=$userId  AND  bookid=$productId";       $this->update($data, $where);    return true;          }else{    $now=time();    $data=array(    'userid'=>$userId,     'bookid'=>$productId,     'nums'=>$nums,     'cartDate'=>$now    );       //$mycartModel=new MyCart();    if($this->insert($data)>0){      /* $this->view->info='添加商品成功';       $this->_forward('ok','global');*/     return true;          }else{      return false;    }       }  }    //从购物车删除商品    //修改商品    //计算购物车的总价  function  getTotalPrice(){    }    //显示购物车  抽象封装某个用户的购物车  function  showMyCart($userId){   $sql='select  b.id,b.name,b.price,m.nums  from book b,mycart m where b.id=m.bookid';   $db=$this->getAdapter();   $res=$db->query($sql)->fetchAll();   //顺带把总价计算出来   //$total_price=0;   for($i=0;$itotal_price+=$bookinfo['price']*$bookinfo['nums'];   }      return $res;  } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值