Easy way to configure child class instances in PHP

Easy way to configure child class instances in PHP

Created:02 Jan 2022 21:10:00

Here is a way of configuring an instances of a inheriting class using a configuration method in its parent class in PHP programming language. The method in the parent class is called configure.


class Produce{

  protected $price = 0.0;
  
  public function __construct($conf){
    $this -> configure($conf);
  }

  public function __get($property){
    return $this -> {$property};
  }

  protected function configure($conf){
    foreach($conf as $name => $property){
      $this -> {$name} = $property;
    }
  }
  
}

class Fruit extends Produce{

  protected $name = '';

  public function __construct($conf){
    $this -> configure($conf);
  }
}

Now instantiate an object and configure it in a nice a clean manner:


$mango = new Fruit([
  'name' => 'Mango',
  'price' => 2.80
]);

This post was updated on 02 Jan 2022 22:23:57


Author, Copyright and citation

Author

Sylwester Wojnowski

Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.

Copyrights

©Copyright, 2022 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.

Citation

Cite this article as:

Wojnowski, Sylwester. "Easy way to configure child class instances in PHP." From sWWW - Code For The Web . https://wojnowski.net.pl//main/index/easy-way-to-configure-child-class-instances-in-php

Add Comment

Allowed BB Code - style tags: [b][/b], [i][/i], [code=text][/code],[code=javascript][/code],[code=php][/code],[code=bash][/code],[code=css][/code],[code=html][/code]


I constent to processing my data given through this form for purposes of a reply by the administrator of this website.

Recent Comments

Nobody has commented on this post yet. Be first!