Skip to content

Instantly share code, notes, and snippets.

@GiancarloJSantos
Forked from AndroxxTraxxon/MyClass.php
Created November 4, 2021 13:23
Show Gist options
  • Save GiancarloJSantos/2d4fdb0589d957078872afe4fd98c8fb to your computer and use it in GitHub Desktop.
Save GiancarloJSantos/2d4fdb0589d957078872afe4fd98c8fb to your computer and use it in GitHub Desktop.
PHP Generic class constructor
<?php
/**
* The important part here isn't the class structure itself, but the
* __construct(...) function. This __construct is generic enough to be placed into any
* data model class that doesn't preprocess its variables,
*
* Even if you want processing on the variables,
* but simply want an initial value from the get-go,
* you can post-process the values after the if($group){...} statement.
*
* This particular class would be able to take objects that look like this:
* ['myVar1'=> $input1, 'myVar2'=>$input2]
* or, exclude one value or the other :
* ['myVar1'=> $input1] or ['myVar2'=>$input2]
*/
use \InvalidArgumentException;
class MyClass{
protected $myVar1;
protected $myVar2;
public function __construct($obj = null, $ignoreExtraValues = false){
if($obj){
foreach (((object)$obj) as $key => $value) {
if(isset($value) && in_array($key, array_keys(get_object_vars($this)))){
$this->$key = $value;
}else if (!$ignoreExtraValues){
throw new InvalidArgumentException(get_class($this).' does not have property '.$key);
}
}
}
}
}
<?php
/**
* This file is really just a demonstration of one possible use of the constructor.
* using an associative array, we can assign values to the class based on their variable names.
*
* Empty constructors are also valid, and nothing will be initialized as the default input is null.
*/
include_once("MyClass.php");
use MyClass;
$sample_variable = new MyClass();
print_r($sample_variable);
$sample_variable = new MyClass([
'myVar2'=>123
]);
print_r($sample_variable);
$sample_variable = new MyClass([
'myVar2'=>123,
'i_dont_want_this_one'=> 'This won\'t throw an error because we turned it off, but it won\'t get added either.'
], true);
print_r($sample_variable);
$sample_variable = new MyClass([
'myVar1'=>123,
'i_dont_want_this_one'=> 'This last one throws an error.'
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment