note 106676 added to language.oop5.abstract
| From: | oliver at ananit dot de | Date: | Sun, 27 Nov 2011 16:07:25 +0000 |
| Subject: | note 106676 added to language.oop5.abstract | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-184692@lists.php.net to get a copy of this message | ||
Abstract classes may have an final constructor, and sometime it makes sense to implement a class
with a final constructor.
<?php
abstract class AbstractModel
{
//our models must use the default constuctor
public final function __construct(){}
public function inject($array){
foreach(array_keys(get_class_vars(get_called_class())) as $property){
$this->$property = $array[$property];
}
}
}
class ProductModel extends AbstractModel
{
public $name;
public $price;
protected $id;
public function getId(){return $this->id;}
}
class Factory{
private $dataSource;
public function __consruct($dataSource){
$this->dataSource = $dataSource;
}
public function get($class, $table, $filter, $orderby, $limit){
$result = array();
foreach($datasource->fetchAssoc($table, $filter, $orderby, $limit) as $rawData){
$obj = new $class();//this can only work if ALL models have a default constructor
$obj->inject($rawData);
$result[] = $obj;
}
return $result;
}
}
?>
Note: This is a very simple example, and I am aware that there are other (better) ways to do this.
Oliver Anan
----
Server IP: 69.147.83.197
Probable Submitter: 88.65.240.10
----
Manual Page -- http://www.php.net/manual/en/language.oop5.abstract.php
Edit -- https://master.php.net/note/edit/106676
Del: integrated -- https://master.php.net/note/delete/106676/integrated
Del: useless -- https://master.php.net/note/delete/106676/useless
Del: bad code -- https://master.php.net/note/delete/106676/bad+code
Del: spam -- https://master.php.net/note/delete/106676/spam
Del: non-english -- https://master.php.net/note/delete/106676/non-english
Del: in docs -- https://master.php.net/note/delete/106676/in+docs
Del: other reasons-- https://master.php.net/note/delete/106676
Reject -- https://master.php.net/note/reject/106676
Search -- https://master.php.net/manage/user-notes.php