0

Как в статическом приватном поле products хранить все созданные продукты(Processors и Ram).Т.е что бы это поле было регистром продуктов

<?php
namespace lesson2;

header('Content-Type: text/html; charset=utf-8');


class User{
private $name;
private $balance;

function __construct($name,$balance){
    $this->name = $name;
    $this->balance = $balance;
}

public function getName(){
    return $this->name;
}

public function getBalance(){
    return $this->balance;
}

public function __toString(){
    return "У пользователя ".$this->getName()." сейчас на счету ".$this->getBalance()."<br/>";
}

public function giveMoney($user, $amount){
    if($amount > $this->balance){
        echo 'Недостаточно средств!'."<br/>";
    }
    else{
        $this->balance = $this->balance - $amount;
        $user->balance = $user->balance + $amount;
        echo "Пользователь ".$this->getName()." перечислил ".$amount." пользователю ".$this->getBalance()."<br/>";
    }

}

}

abstract class Product{
private $name;
private $price;
private $owner;
static private $products;

public function setOwner(User $user){
    $this->owner = $user;
}

function __construct($name, $price, $owner){
    $this->name = $name;
    $this->price = $price;
    $this->owner = $owner;
}

}

class Processor extends Product{
private $frequency;

}

class Ram extends Product{
private $type;
private $memory;
}

1 ответ 1

1

Если я правильно понял вопрос то речь шла об этом:

abstract class Product
{
    static private $products = [];
    
    public static function setProducts($product)
    {
        self::$products[] = $product;
    }
    
    public static function getProducts()
    {
        return self::$products;
    }
}

class Processor extends Product
{
    private $frequency;
}

class Ram extends Product
{
    private $type;
    private $memory;
}

Ram::setProducts('item1');
Processor::setProducts('itemProc1');
Processor::setProducts('itemProc2');

print_r(Ram::getProducts());
print_r(Processor::getProducts());

Результат:

Array
(
    [0] => item1
    [1] => itemProc1
    [2] => itemProc2
)
Array
(
    [0] => item1
    [1] => itemProc1
    [2] => itemProc2
)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.