意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

PHP中属性和方法的定义

来源:恒创科技 编辑:恒创科技编辑部
2024-01-05 11:25:59
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编程,在类中定义的函数与类同名时,这个函数将会被PHP认为是构造函数。当创建一个类的实例时,将会自动调用构造函数。
构造函数主要有以下特点:
• 构造函数的函数名和类名必须完全相同;
• 构造函数没有返回类型和返回值;
• 构造函数的主要功能是对类中的对象初始化。
注意:构造函数既可以为有参函数,也可以为无参函数。
​​PHP​​类中的特殊的方法
构造函数__construct
功能:可以创建函数的构造函数
例如:
<?php
class Php
{
function __ construct() //构造函数
{
print “This is www.phpdo.net”;
}
}
$myclass = new Php;
?>
结果:This is www.phpdo.net
注意:__construct前面的下斜线为两个“_”
析构函数__destruct功能:析构函数可以销毁对象。
例如:
<?php
class Php
{
function __destruct() //析构函数
{
print “This is www.phpdo.net!;
}
}
$MyClass = new Php;
$MyClass = null;
?>
结果:This is www.phpdo.net!
字符串转换函数__toString
功能:因为print和echo输出数据类型为对象的数据,所以就有了__toString
例如:
<?php
class Myclass
{
var $name;
function __construct($name)
{
$this->name = $name;
}
}
$myclass = new Myclass(“Simon”);
echo $myclass;
?>
使用__toString之后呢?
例如:
<?php
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;$i<count($res);$i++){
$bookinfo=$res[$i];
$this->total_price+=$bookinfo['price']*$bookinfo['nums'];
}
return $res;
}
}


PHP中属性和方法的定义

上一篇: 韩顺平 php视频教程 笔记心得 zend.framework.第16讲.综合应用-购物车2 下一篇: php jquery ajax json 全国省市区三级联动下拉列表 简单实现