PHP is equivalent to C # `: base`

What will be the equivalent of the PHP code for the snippets below:

C # code:

class Composite : Component { private List<Component> _children = new List<Component>(); // Constructor public Composite(string name) : base(name) { } } 

PHP code?

I'm often looking for a section : base(name) . A complete link to the code in C # can be found here http://www.dofactory.com/Patterns/PatternComposite.aspx

+4
source share
2 answers

PHP equivalent

 class Foo extends Bar { public function __construct($param) { parent::__construct($param); } } 

This is explicitly mentioned in the PHP documentation for constructors .

You must keep in mind the important difference between C # and PHP: in PHP, unless you explicitly call the base constructor, it will not be called at all! This is not the same as in C #, where the base constructor is always invoked (although you can omit the explicit call if there is an open constructor without parameters).

+7
source

You are looking for parent - an accessor for the parent class.

Via parent you can call the constructor of the base class: parent::__construct($param, $param2)

See: http://php.net/manual/en/keyword.parent.php

Note that this happens directly in the constructor, for example:

 public function __construct($x) { parent::__construct($x); } 
+4
source

Source: https://habr.com/ru/post/1412632/


All Articles