찾다
php教程PHP源码商城购物车以PHP单例模式实现。

1. [代码][PHP]代码   

<?php
class Cart{
    static protected $ins;          //实例变量
    protected $item = array();       //放商品容器
    //禁止外部调用
    final protected function __construct(){
    }

    //禁止克隆
    final protected function __clone(){
    }

    //类内部实例化
    static protected function Getins(){
        if(!(self::$ins instanceof self)){
            self::$ins = new self();
        }
        return self::$ins;
    }

    //为了能使商品跨页面保存,把对象放入session里
    public function Getcat(){
        if(!($_SESSION[&#39;cat&#39;]) || !($_SESSION[&#39;cat&#39;] instanceof self)){
            $_SESSION[&#39;cat&#39;] = self::Getins();
        }
        return $_SESSION[&#39;cat&#39;];
    }

    //入列时的检验,是否在$item里存在.
    public function Initem($goods_id){
        if($this->Gettype() == 0){
            return false;
        }
        if(!(array_key_exists($goods_id,$this->item))){
            return false;
        }else{
            return $this->item[$goods_id][&#39;num&#39;];   //返回此商品个数
        }
    }

    //添加一个商品
    public function Additem($goods_id,$name,$num,$price){
        if($this->Initem($goods_id) != false){
            $this->item[$goods_id][&#39;num&#39;] += $num;
            return;
        }
        $this->item[$goods_id] = array();               //一个商品为一个数组
        $this->item[$goods_id][&#39;num&#39;] = $num;           //这一个商品的购买数量
        $this->item[$goods_id][&#39;name&#39;] = $name;         //商品名字
        $this->item[$goods_id][&#39;price&#39;] = $price;       //商品单价
    }

    //减少一个商品
    public function Reduceitem($goods_id,$num){
        if($this->Initem($goods_id) == false){
            return;
        }
        if($num > $this->Getunm($goods_id)){
            unset($this->item[$goods_id]);
        }else{
            $this->item[$goods_id][&#39;num&#39;] -=$num;
        }
    }

    //去掉一个商品
    public function Delitem($goods_id){
        if($this->Initem($goods_id)){
            unset($this->item[$goods_id]);
        }
    }

    //返回购买商品列表
    public function Itemlist(){
        return $this->item;
    }

    //一共有多少种商品
    public function Gettype(){
        return count($this->item);
    }
    
    //获得一种商品的总个数
    public function Getunm($goods_id){
        return $this->item[$goods_id][&#39;num&#39;];
    }

    // 查询购物车中有多少个商品
    public function Getnumber(){
        $num = 0;
        if($this->Gettype() == 0){
            return 0;
        }
        foreach($this->item as $k=>$v){
            $num += $v[&#39;num&#39;];
        }

        return $num;
    }

    //计算总价格
    public function Getprice(){
        $price = 0;
        if($this->Gettype() == 0){
            return 0;
        }
        foreach($this->item as $k=>$v){
            $price += $v[&#39;num&#39;]*$v[&#39;num&#39;];
        }
        return $price;
    }

    //清空购物车
    public function Emptyitem(){
        $this->item = array();
    }
}
/*
     自己测试代码也拿出来
*/
?php
include_once(&#39;Cart.php&#39;);
$cart = Cart::Getcat();
$cart->Additem(&#39;1&#39;,&#39;谍匪&#39;,&#39;5&#39;,&#39;9999&#39;);
print_r($cart);

                   

                   

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경