Php classes default values

Set default variables in class

This is working fine but my question is: Isn’t there any way to set that values automatically in setting new class? Something like:

$newArt = new Article("content of content variable", "author"); 

3 Answers 3

public function __construct($content, $author) < $this->content = $content; $this->author = $author; $this->all = "author> Wrote: content>"; > 

Other ways depending on the goal, but how does $this->content and $this->author get set in your existing code?

slight modifcation to @AbraCadaver (not enough rep to add comment yet)

public function __construct($content='my default content', $author='my default author') < $this->content = $content; $this->author = $author; $this->all = "author> Wrote: content>"; > 

I’m suggesting this because it looks like the OP doesn’t require parameters on construction. This way it can be instantiated without passing anything and if nothing is passed it defaults to some predefined values.

another approach would be:

public function __construct() < $this->content = 'my default content'; $this->author = 'my default author'; $this->all = "author> Wrote: content>"; > 

and then use functions like this to set the values later:

public set_author ($author) < $this->author = $author; > 

I prefer keeping variables private and then building set and get public functions myself. It leaves room for validation and formatting rules to be added later.

Источник

how to create default value for for an object? PHP

let’s say I have a Human class which has the variable of $gender which doesn’t have any value assigned into it. Human has a constructor with the parameter of age, gender, height and weight. I have another class called Female which inheritance from Human but now the Female class is overriding the $gender variable with a string of Female . When I create the object let’s say $f = new Female(12, ‘female’, 123, 40); How can I skip typing the female when creating the object? I thought we need to create another new constructor in Female class which I did and in the Female class constructor’s parameter I have age, gender = ‘female’, height and weight but this doesn’t seem to work. I tried leaving the gender part empty when creating the object or tried entering empty string such as «» . Can someone give me a hand please? Thanks a lot. Code for my human class

class Human < protected $age = 0; protected $gender; protected $height_in_cm; protected $weight_in_kg; function __construct($age, $gender, $heightCM, $weightKG) < $this->age = $age; $this->gender = $gender; $this->height_in_cm = $heightCM; $this->weight_in_kg = $weightKG; > /** * @return int */ public function getAge() < return $this->age; > /** * @return string */ public function getGender() < return $this->gender; > > 
require_once('Human.php'); class Female extends Human< protected $gender = 'female'; function __construct($age, $gender = 'female', $heightCM, $weightKG) < $this->age = $age; $this->gender = $gender; $this->height_in_cm = $heightCM; $this->weight_in_kg = $weightKG; > > $f = new Female(12,'female',123,40); echo "Your gender is ". $f->getGender()."
";

the whole idea is not correct (from my point of view), I mean if you want to classify Human to Male and Female classes then why do you bother your self with a $gender parameter in the constructor, if i were you, i would omit that parameter and set it implicitly to «male» in the Male class and «female» in the Female

@Abdo Adel ah! I get what you mean, it’ll be more of being redundant since I have to set default value in male and female why bother having the variable in human right? But then will have to set the getGender in both male and female instead of just set the getGender in Human. Is there much a difference? Sorry still in a long learning process.

@Dora No I didn’t mean to omit the attribute $gender from the class, I meant to omit it from the constructor and set it manually in the constructor ( $this->gender = ‘male’ in the Male class and the same for Female ), this way you will avoid redundancy of specifying the gender every time you make an object and also the function getGender inherited from Human still works

Источник

Как в PHP в классе свойствам назначать значения по умолчанию объекты.?

Можно ли как то указать что там массив объектов? Может использовать «new class» или как то еще ананимное объявление можно использовать?

Простой 4 комментария

Compolomus

Compolomus

Dier_Sergio_Great

Дмитрий, Я бы перестал статику писать, но фреймворк Joomla Framwork кое где написан через одно место.

Dier_Sergio_Great

Дмитрий, Я так примерно вынужден был сделать. Я в конструкторе проходил по массиву и применял к ним приведение к типу (object).

Vitaly48

 ['name' => 'Рублей', 'short' => '₽', 'ratio' => 1, 'default' => 1, 'display' => 1], 'USD' => ['name' => 'Dollar', 'short' => '$', 'ratio' => 1, 'default' => 1, 'display' => 1], 'EUR' => ['name' => 'Euro', 'short' => '€', 'ratio' => 1, 'default' => 1, 'display' => 1], 'GBP' => ['name' => 'Pound', 'short' => '£', 'ratio' => 1, 'default' => 1, 'display' => 1], 'JPY' => ['name' => '円', 'short' => '¥', 'ratio' => 1, 'default' => 1, 'display' => 1], 'CNY' => ['name' => '元', 'short' => 'Ұ', 'ratio' => 1, 'default' => 1, 'display' => 1], ]; public function code(): string < return $this->value; > public function name(): string < $this->insureValue(); return self::DATA[$this->value]['name']; > public function short(): string < $this->insureValue(); return self::DATA[$this->value]['short']; > public function ratio(): string < $this->insureValue(); return self::DATA[$this->value]['ratio']; > public function default(): string < $this->insureValue(); return self::DATA[$this->value]['default']; > public function display(): string < $this->insureValue(); return self::DATA[$this->value]['display']; > private function insureValue(): void < if (!isset(self::DATA[$this->value])) < throw new InvalidArgumentException($this->value); > > > echo CurrenciesEnum::RUB->code(), PHP_EOL; echo CurrenciesEnum::RUB->name(), PHP_EOL; echo CurrenciesEnum::RUB->short(), PHP_EOL;
name; > public function name(): string < return self::getField($this->name, 'name'); > public function short(): string < return self::getField($this->name, 'short'); > public function ratio(): string < return self::getField($this->name, 'ratio'); > public function default(): string < return self::getField($this->name, 'default'); > public function display(): string < return self::getField($this->name, 'display'); > private static function getField(string $currency, string $field): string < $data = [ self::RUB->name => ['name' => 'Рублей', 'short' => '₽', 'ratio' => 1, 'default' => 1, 'display' => 1], self::USD->name => ['name' => 'Dollar', 'short' => '$', 'ratio' => 1, 'default' => 1, 'display' => 1], self::EUR->name => ['name' => 'Euro', 'short' => '€', 'ratio' => 1, 'default' => 1, 'display' => 1], self::GBP->name => ['name' => 'Pound', 'short' => '£', 'ratio' => 1, 'default' => 1, 'display' => 1], self::JPY->name => ['name' => '円', 'short' => '¥', 'ratio' => 1, 'default' => 1, 'display' => 1], self::CNY->name => ['name' => '元', 'short' => 'Ұ', 'ratio' => 1, 'default' => 1, 'display' => 1], ]; if (!isset($data[$currency])) < throw new InvalidArgumentException($currency); >return $data[$currency][$field]; > > echo CurrenciesEnum::RUB->code(), PHP_EOL; echo CurrenciesEnum::RUB->name(), PHP_EOL; echo CurrenciesEnum::RUB->short(), PHP_EOL;

Класс CurrencyStorage

final class CurrenciesStorage < private static self|null $instance = null; /** @var Currency[] */ private array $currencies = []; private function __construct() < >public static function getInstance(): self < if (self::$instance === null) < self::$instance = new self(); >return self::$instance; > public function add(Currency $currency): void < $this->currencies[$currency->code] = $currency; > public function has(string $code): bool < return isset($this->currencies[$code]); > public function get(string $code): Currency|null < return $this->currencies[$code] ?? null; > public function all(): array < return $this->currencies; > >

Потом при инициализации своего модуля тебе нужно будет создать инстанс сторажда и заполнить его дефолтными значениями:

$storage = CurrenciesStorage::getInstance(); $storage->add(new Currency('RUB', 'Рублей', '₽')); $storage->add(new Currency('USD', 'Dollar', '$')); $storage->add(new Currency('EUR', 'Euro', '€'));
// Получить данные по одному объекту echo $storage->get('RUB')->code, PHP_EOL; echo $storage->get('RUB')->name, PHP_EOL; echo $storage->get('RUB')->short, PHP_EOL; // Получить все объекты var_dump($storage->all());

Данный код в объектном стиле, в IDE будут работать подсказки, у стораджа есть тайпхинтинк (соответственно туда ничего кроме currency нельзя буде запихнуть). Плюс работает инкапсуляция, т.к. свойства у currency readonly их нельзя будет изменить в другом коде

Источник

Читайте также:  Vue js use css
Оцените статью