Typically, you should write constructors for your classes in some way that the "child" class initializes the superclass so that everything is consistent.
abstract class Product { private $name; private $price; //more methods public __construct($name, $price){ $this->name = $name; $this->price =$price; } } class Smartphone extends Product{ private $brand; private $os; // default value to $os: like that, we can create a Smartphone whitout an os public __construct($name, $price, $brand, $os = null){ parent::__construct($name, $price); $this->brand = $brand; $this->os =$os; } } class Computer extends Product { private $cpuFrequency; private $ram; // default value to $ram: with this, we can create a Computer whiout ram public __construct($name, $price, $frequency, $ram = null){ parent::__construct($name, $price); $this->frequency = $frequency; $this->ram =$ram; } }
Then, to create a computer, you can do, for
$computer = new Computer('notBuiltToWindows', 560 , 2.0, 4);
or, to create a Nexus in your example:
$nexus = new Smartphone($name, $price, $frequency, $ram);
and to create a smartphone without a ram
$nexus = new Smartphone($name, $price, $frequency);