Last active
December 17, 2015 01:49
-
-
Save kosinix/5530866 to your computer and use it in GitHub Desktop.
PHP class setter and getter generator. These functions can be added to a class to generate setter and getter functions for that class. Will save you a lot of typing when your class has many class variables.
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 | |
/** | |
* Our example class | |
*/ | |
class Person { | |
/** | |
* Class properties to generate the setter and getter functions | |
*/ | |
protected $height; | |
protected $weight; | |
protected $eye_color; | |
protected $hair_color; | |
public function __construct(){ | |
// Constructor | |
} | |
public function example_class_function(){ | |
// Some function | |
} | |
/** | |
* ADD THE FUNCTIONS BELOW INTO YOUR CLASS. BE SURE TO DELETE AFTER USE OR WHEN YOUR CODE GOES LIVE | |
*/ | |
/** | |
* Generate setter functions | |
*/ | |
public static function generate_setter_functions(){ | |
$class_vars = get_class_vars(__CLASS__); | |
foreach ($class_vars as $name => $value) { | |
self::debug( ' | |
public function set_'.$name.'( $value ){ | |
$this->'.$name.' = $value; | |
}' ); | |
} | |
} | |
/** | |
* Generate getter functions | |
*/ | |
public static function generate_getter_functions(){ | |
$class_vars = get_class_vars(__CLASS__); | |
foreach ($class_vars as $name => $value) { | |
self::debug( ' | |
public function get_'.$name.'(){ | |
return $this->'.$name.'; | |
}' ); | |
} | |
} | |
/** | |
* Print with a twist! | |
*/ | |
public static function debug($o){ | |
echo '<pre>'.print_r($o, 1).'</pre>'; | |
} | |
/** | |
* END OF GENERATOR FUNCTIONS! | |
*/ | |
} | |
/** | |
* USAGE | |
*/ | |
Person::generate_setter_functions(); | |
Person::generate_getter_functions(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment