Easy Camel Case conversion in PHP

I was looking at a couple of classes the today from a very old piece of code and found a little gem of a function to convert variable names into CamelCase function names that I wrote a while back and thought I should share it.

The function itself is incredibly simple and uses preg_replace() and ucword() to convert a variable name into CamelCase.

public function makeCamelCase($name) {
    return preg_replace('/(?:^|_)(.?)/e', "strtoupper('$1')", $name);
}

This is very powerful when used in conjunction with object getter and setter methods since you can convert a variable name into it’s getter or setter method with:

$getter = sprintf('get%s', makeCamelCase('contact_number'));
$setter = sprintf('set%s', makeCamelCase('contact_number'));

This will make the value of $getter “getContactNumber” and $setter “setContactNumber”. Which allows you to then use the values to get and set methods to save / retrieve data from a submission.

$getter = sprintf('get%s', makeCamelCase('contact_number'));
$setter = sprintf('set%s', makeCamelCase('contact_number'));

$user = new User();
$user->$setter($contact_number);

echo $user->$getter();

Leave a Reply

Your email address will not be published. Required fields are marked *