dongpi3237 2013-04-25 17:44
浏览 35
已采纳

OOP - 类和子类 - 调用子类方法[关闭]

I was wondering if this syntax is correct:

On Classes.php:

Class Cart {

   public $Product; // an object handler will be set on this property

   public function __construct($user) {
   // get a product on user's cart (let's say it's only 1 product) - returns $id
   $this->Product = new Product($id);
   }
}


Class Product {

   public function __construct($id) {
   // construct goes here
   }

   public function Product_Method() {
   // product method goes here
   }

}

On Script

$cart = new Cart($user);
$product_method = $cart->Product->Product_method();

It looks alright to me, since $product is set as Public and refers to an object handler.

  • 写回答

3条回答 默认 最新

  • doufei2355 2013-04-25 18:11
    关注

    There are various things you could mean by "correct" here.

    1. Syntax

      Your syntax is correct. You could have easily discovered this by running your code, so I'm not sure if this is what you're asking about.

    2. Correctness

      As others have said, $id isn't present in the scope of the constructor. This will result in a runtime error.

    3. Best Practices

      Dependency injection is all the rage these days. Calling new from a constructor is discouraged. Instead, you'd pass in your Product object. Note that this is somewhat subjective, if that sounds unnecessarily complicated nothing forces you do it, but at least be aware of why people are against it so that you can make an informed decision.

      Also, depending on your use case, it may be better to encapsulate the functionality so that outside code doesn't have to know about Product's methods (it just has to deal with a cart). That is, make $Product private and add a method to Cart that is responsible for calling Product_method(). This may or may not make sense depending on the semantics of Product_method() (is it something that a Cart should know how to do?).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并