Last active
December 17, 2015 08:49
-
-
Save 321zeno/5583174 to your computer and use it in GitHub Desktop.
A simple class to initialize objects to use with Mustache.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Core_Base | |
{ | |
/** | |
* the constructor will assign | |
* - the values specified in the constructor's arguments, in that specific order as the object's properties | |
* - if an array is passed as argument, the values from that array will be passed as the object's properties | |
* - the object's properties which have no value assigned will be set to false to prevent name collisions in the mustache templates | |
*/ | |
public function __construct(){ | |
$properties = get_object_vars($this); | |
$arguments = func_get_args(); | |
if (is_array($arguments[0])){ | |
$obj = $arguments[0]; | |
foreach ($properties as $key => $value) { | |
if (isset($obj[$key])){ | |
$this->{$key} = $obj[$key]; | |
} else { | |
$this->{$key} = false; | |
} | |
} | |
} else { | |
$i = 0; | |
foreach ($properties as $key => $value) { | |
if (isset($arguments[$i])){ | |
$this->{$key} = $arguments[$i]; | |
} else { | |
$this->{$key} = false; | |
} | |
$i++; | |
} | |
} | |
} | |
} | |
/*** use ***/ | |
class Core_Page extends Core_Base | |
{ | |
public $title; | |
public $content; | |
} | |
/*** init ***/ | |
$page = new Core_Page('Fun Fact', 'Polar bears are left handed.'); | |
//or | |
$page = new Core_Page(array( | |
'title' => 'Fun Fact', | |
'content' => 'Many hamsters only blink one eye at a time.' | |
)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment