Y
Y
Yuri Ryabkov2021-08-24 12:43:11
PHP
Yuri Ryabkov, 2021-08-24 12:43:11

How to implement creation of products array with show method?

Hello everyone, help me implement the creation of an array that consists of objects (classes) and display it on the page using the show method (which is described in the Product class), thanks in advance.

class Product 
{
public $name;
public $price;
public $description;
public $brand; 
public function __construct($name, $price,$description,$brand)
{
 $this->name = $name;
 $this->price = $price;
 $this->description = $description;
 $this->brand = $brand;
}
function show() {
    return 'Name: '.$this -> name .' Price:'.$this->price .'Description:'.$this->description. ' Brand:'. $this->brand; 
}
}
// $y = new Product('Iphone X ', '$1500 ', 'Phone ', 'Apple ');
// echo $y -> show();
 
class Phone extends Product {
        protected $cpu;
        protected $ram;
        protected $sim;
        protected $hdd;
        protected $os;
        function __construct($name,$price,$description,$brand,$cpu,$ram,$sim,$hdd,$os)
{
parent:: __construct($name,$price,$description,$brand);
        $this->cpu = $cpu;
        $this->ram = $ram;
        $this->sim = $sim;
        $this->hdd = $hdd;
        $this->os = $os;
}
function show(){
        parent:: show();
        echo 'CPU: '.$this->cpu .'RAM: ' .$this->ram .'SIM: ' .$this->sim .'HDD: ' .$this->hdd .'OS: ' .$this->os;
}
}
 
   
class Monitor extends Product{
      protected  $diagonal;
      protected  $frequency;
      protected  $ports;
function __construct($name,$price,$description,$brand,$diagonal,$frequency,$ports)
 
{
parent:: __construct($name,$price,$description,$brand);
        $this->diagonal = $diagonal;
        $this->frequency = $frequency;
        $this->ports = $ports;
}        
 function show(){
        parent:: show();
        echo 'Diagonal: '.$this->diagonal .'Frequency: ' .$this->frequency .'Ports: ' .$this->ports;
}       
}   
 
     
     
     
$prod = [
 $x = new Phone('Iphone X ', '$1500 ', 'Phone ', 'Apple ', 'A9 ', '1024 ', '1 ', '128gb ', 'Ios '),
 $mon = new Monitor('Abracadabra ', '$1500 ', 'Monitor ', 'DELL ', '24 ', '144ghz ', 'HDMI '),
   $mon1 = new Monitor('ROG ', '$1500 ', 'Monitor ', 'ASUS ', '24 ', '144ghz ', 'HDMI ')
        
        ];

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-08-24
@Tushu_svet

Teaching light!

$prod = [
 	'x' => new Phone('Iphone X ', '$1500 ', 'Phone ', 'Apple ', 'A9 ', '1024 ', '1 ', '128gb ', 'Ios '),
 	'mon' => new Monitor('Abracadabra ', '$1500 ', 'Monitor ', 'DELL ', '24 ', '144ghz ', 'HDMI '),
  	'mon1' => new Monitor('ROG ', '$1500 ', 'Monitor ', 'ASUS ', '24 ', '144ghz ', 'HDMI ')
];

foreach($prod as $p) $p->show();

Share PHP code online

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question