Created
June 3, 2011 16:21
-
-
Save mfields/1006626 to your computer and use it in GitHub Desktop.
Making some Objects in PHP
This file contains hidden or 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 | |
| /* | |
| * Send all required arguments. | |
| */ | |
| $test = new My_Object( array( | |
| 'one' => 1, | |
| 'two' => 2, | |
| 'three' => 3, | |
| ) ); | |
| print '<pre>'; | |
| gettype( $test ); // Should be "My_Object" | |
| var_dump( empty( $test ) ); // false as expected. | |
| var_dump( $test ); | |
| print '</pre>'; | |
| /* | |
| * This object is missing one required argument. | |
| */ | |
| $test = new My_Object( array( | |
| 'one' => 1, | |
| 'two' => 2, | |
| ) ); | |
| print '<pre>'; | |
| gettype( $test ); // Would be neat if this could return some sort of error object. | |
| var_dump( empty( $test ) ); // Even though all properties have been removed, this still returns false? | |
| var_dump( $test ); | |
| print '</pre>'; | |
| class My_Object { | |
| public $one = null; | |
| public $two = null; | |
| public $three = null; | |
| public function __construct( $args = array() ) { | |
| $diff = array_diff_key( get_object_vars( $this ), $args ); | |
| if ( ! empty( $diff ) ) { | |
| /* Let them know they're doing it wrong. */ | |
| trigger_error( 'Could not construct object.' ); | |
| /* It's possible to kill all of the properties. */ | |
| foreach( array_keys( get_object_vars( $this ) ) as $property ) { | |
| unset( $this->$property ); | |
| } | |
| /* Anyway to change type of object before return? */ | |
| return; | |
| } | |
| $this->one = (int) $args['one']; | |
| $this->two = (int) $args['two']; | |
| $this->three = (int) $args['three']; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I meant "others using the code" as in anyone who forks your project or uses it as a base/inspiration for their own system.
Now that I know what you're trying to do (rather than mucking around with
My_Objects and$tests), have you considered using a factory method?Basically:
Then
$testwill either be an instance of Icon_Set or some custom error object if it was configured improperly.(OK, it's not a real factory method ... but similar enough ...)