OOP - 类和子类 - 呼叫子方法

OOP - 类和子类 - 呼叫子方法

问题描述:

我在想,如果这个语法是正确的:OOP - 类和子类 - 呼叫子方法

在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 
    } 

} 

论文字

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

它看起来佯装我,因为$ product被设置为Public,并且引用一个对象处理程序。

+0

什么是Product_method()我在定义中看不到 – 2013-04-25 17:45:11

+0

是什么问题? – Cooper 2013-04-25 17:47:10

+0

你为什么不尝试在你的计算器?一个有用的相关问题:http://*.com/questions/2307097/method-chains-php-oop – 2013-04-25 17:47:21

有,你可以通过“正确”的意思是这里的各种事情。

  1. 语法

    你的语法是正确的。你可以通过运行你的代码很容易地发现这一点,所以我不确定这是否是你问的。

  2. 正确性

    正如其他人所说,$id不存在构造函数的范围。这将导致运行时错误。

  3. 最佳实践

    Dependency injection是所有的愤怒,这些天。不鼓励从构造函数调用new。相反,您会传入Product对象。请注意,这是有点主观的,如果这听起来不必要复杂没有什么部队你这样做,但至少要知道为什么人们反对它,以便你可以做出明智的决定。

    另外,根据您的使用情况,封装功能可能会更好,以便外部代码不必知道Product的方法(它只需处理购物车)。也就是说,使$Product专用,并将方法添加到Cart负责调用Product_method()。根据Product_method()的语义(这是Cart应该知道该怎么做?),这可能有意义或无意义。

+0

也只是一个术语nitpick:'Product'不是“子类”。该术语严格地指[继承](http://en.wikipedia.org/wiki/Inheritance_ \(面向对象的程序设计))。你在做什么是[作文](http://en.wikipedia.org/wiki/Object_composition)。 – 2013-04-25 18:18:17

+0

亲爱的Matt,感谢您的详细回复。它完全解决了我的疑问,但给了我想想问题的另一个方面。关于依赖注入,我可以请你澄清这段话:“相反,你会传入你的产品对象”。我没有看到提出的“出路”。 – 2013-04-25 18:20:33

+0

从我写这篇文章开始,看看你的新评论和编辑,你的确在问语法。 [如果你得到错误](http://*.com/questions/16221318/oop-classes-and-subclasses-call-subclass-method/16221756#comment23200762_16221318)知道它们是什么会有帮助;也许你应该发布一个新的,更具体的问题。 – 2013-04-25 18:20:41

您在构造函数中使用$ id将它传递给new Product($id),但是您从哪里获取$ id?而且你只有一个字符串在函数中浮动,没有回声或分配给变量。

+0

我没有放过整个类,因为疑问与此有效性有关:$ class-> property-> method()。作为属性在__construct上创建的对象处理程序 – 2013-04-25 17:58:29

$ id是什么?你需要设置的$ id在构建

Class Cart { 

    public $Product; 

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

,并在你的代码

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