php设计模式之面向对象基础知识

发布时间:2020-08-06 12:16:48 作者:zhou604638018
来源:网络 阅读:366

类是产生对象的工厂,它由属性和方法组成。属性代表对象的状态,方法代表对象的操作行为

对象是由类产生,拥有该类定义的所以属性与方法。

对象A知道对象B,但对象B不知道对象A : 订单含有商品,但商品不包含订单

php设计模式之面向对象基础知识

/**
 * 商品
 * Class Goods
 */
class Goods{
    private $_name = null;
    private $_price = 0;

    public function __construct($name,$price) {
        $this->_name = $name;
        $this->_price = $price;
    }

    /**
     * @return null
     */
    public function getName() {
        return $this->_name;
    }

    /**
     * @return int
     */
    public function getPrice() {
        return $this->_price;
    }


}

/**
 * 订单
 * Class Order
 */
class Order{

    private $_goods = [];

    public function addGoods(Goods $goods){
        $this->_goods[] = $goods;
    }

}

    2. 双向关联

        对象A知道对象B,对象B也知道对象A,两个对象之间可以相互调用方法与属性。如:订单与客户之间的关系

    php设计模式之面向对象基础知识

class Customer{

    public $orders=[];

    private $_id;

    public function __construct($id) {
        $this->_id = $id;
    }

    public function addOrder(Order $order){
        $this->orders[] = $order;
    }

    public function getOrder(){
        return $this->orders;
    }

}

class Order{

    public function getCustomerByOrderId($orderId){
        //通过订单号,找到用户id
        $id = 23;
        return  new Customer($id);
    }

}




推荐阅读:
  1. python面向对象的基础知识
  2. php设计模式之——原型模式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php 设计模式 对象之间

上一篇:重置Solaris10 root 密码

下一篇:EndPoint学习之路_管理维护篇:Gaia.ISO的SSH访问设置

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》