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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?