-
-
Save mfields/1006626 to your computer and use it in GitHub Desktop.
<?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']; | |
} | |
} |
Cool! Other people using the object is totally not permitted. My intention is to only use it internally in a plugin. Basically there would be a configuration array for "Icon Sets" that is filterable. This array would be looped over and a new Icon_Set object will be created only if it is configured properly.
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_Object
s and $test
s), have you considered using a factory method?
Basically:
$test = create_my_object( $args );
function create_my_object( $args = array() ) {
if ( Icon_Set::check_args( $args ) ) {
return new Icon_Set( $args );
} else {
return new My_Error( "You're doing it wrong!" );
}
}
Then $test
will 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 ...)
Kind of like pre-validation? I think that would work ... but you'd need to document it well so others using the code would remember to use it before they instantiate their object.