Last active
June 18, 2022 09:28
-
-
Save AndroxxTraxxon/6bb8bd370c6b7ad9f48ccd612c7b5d83 to your computer and use it in GitHub Desktop.
PHP Generic class constructor
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 | |
/** | |
* 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); | |
} | |
} | |
} | |
} | |
} |
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 | |
/** | |
* 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.' | |
]); |
Thank you very much.
Great, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this!