Setter and getter generator for PHP (script)

Edited 02. Dec 2010, 14:24
Published 10. Nov 2010, 15:09
Files setnget_gen.php
Pages
  1. Setter and getter form
  2. Setter and getter function for PHP (for offline use)

Here's a PHP function that is used to generate setter and getter methods.

Here's an example of how to use the script. Simply create an array, fill it with the properties you want and call the function. Notice that arrays can be given as well, this is in case you want the setters and getters to point to a different named property (see the output for an example).

$arr = array(
	'foo',
	array('bar', '_bar'),
	'chickenCheese'
);

setnget_gen($arr, 2);

Here's the output from the script. This is the exact output that is given if the script is run in a browser. Now you can simply copy and paste your fresh setters 'n' getters in your class.

function setFoo($foo) { $this->foo = $foo; }
function getFoo() { return $this->foo; }
function setBar($bar) { $this->_bar = $bar; }
function getBar() { return $this->_bar; }
function setChickenCheese($chickenCheese) { $this->chickenCheese = $chickenCheese; }
function getChickenCheese() { return $this->chickenCheese; }

Now you're probably wondering what that second argument in the function means. This argument decides whether or not to use CamelCase or not. If the number 1 is given instead of 2, the methods will be written in lowercase and word seperated by underscores.

Personally I like to work with a local server (I'm using Apache with XAMPP), then I'm able to immideately generate my setters and getters. I simply keep the generator page in a tab on my browser and refresh it whenever I need to.

Let's try the same example without camelcase. Notice that I've changed the chickenCheese string to chicken_cheese to comply with the other format.

$arr = array(
	'foo',
	array('bar', '_bar'),
	'chicken_cheese'
);

setnget_gen($arr, 1);

Here's the output of the lowercased version.

function set_foo($foo) { $this->foo = $foo; }
function get_foo() { return $this->foo; }
function set_bar($bar) { $this->_bar = $bar; }
function get_bar() { return $this->_bar; }
function set_chicken_cheese($chicken_cheese) { $this->chicken_cheese = $chicken_cheese; }
function get_chicken_cheese() { return $this->chicken_cheese; }

Enjoy.

Files

View Source: setnget_gen.php
Download: setnget_gen.php

Back to the top