Uly's Journal

UlyCO

Books

Comics

Cooking

Journal

Coffee

Roasting

Resume

Valhallacon 2009

PHP Functions

I do PHP, off and on, both at work and at home. I often find my various include files getting cumbersome. I mostly just want a way to have a bunch of easily callable functions, that are easy to organize and edit. Yesterday, I came up with this solution.

First, create a function which, when given string 'string', checks to see if 'string' exists as a function, and if not, looks in a separate directory or directories, and requires a file that is named 'string.php'. All that will be in 'string.php' are the php tags, and a function definition for 'string'.

So, I include this in my common.php:

	if (! function_exists('add_func')) {
		function add_func ($function) {
			if (! function_exists($function)) {
				$func_path = array('/home/ulysses/funcs');
				foreach ($func_path as $func_dir) {
					$func_file = "$func_dir/$function.php";
					if (file_exists($func_file)) {
						require $func_file;
						return;
					}
				}
				die("add_func: $function not a file-specified function.\n");
			}
		}
	}
	add_func('call_func');

At the end there, I use add_func to also define call_func. What call func does is first call add_func, to make sure whatever function it's calling is defined, and then it runs that function:

	function call_func() {
		$args = func_get_args();
		$func = array_shift($args);
		add_func($func);
		call_user_func_array($func,$args);
	}

Not the most complex thing ever, but a pretty easy way of setting up what I want.

previous || next

Privacy Policy 
All material Copyright © 2003–2009 Ulysses Somers, except where otherwise noted.