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条)

报告相同问题?