An Entrepreneur, Coach, IT Consultant, Strategic Adviser, and a Traveler craving to explore and contribute to forming a better society.

Thursday, January 22, 2009

Overriding internal function names

No comments :

Overriding internal function names

While oftentimes, the internal functions in PHP provide great utility, sometimes they don't do exactly what we want them to. We may need to augment their behavior to match what we want the function to do, but we also want to redefine the function with another name to avoid further cluttering the scope.

The filesystem functions are one area where we may want to do this. Let's say we want to make sure any file created by file_put_contents() has certain permissions set. For example, let's say we want the files created by this to be read-only; we can redefine the function in a new namespace, as shown below.

Listing 11. Defining file_put_contents() inside a namespace

namespace Foo;

function file_put_contents( $filename, $data, $flags = 0, $context = null )
$return = \file_put_contents( $filename, $data, $flags, $context );

chmod($filename, 0444);

return $return;

We call the internal file_put_contents() function inside the function and prefix the function name with a backslash to indicate that it should be handled in the global scope, which means the internal function will be called. After calling the internal function, we then chmod() the file to set the appropriate permissions.

These are just a few examples of how we can use namespaces to enhance our code. In each case, we avoid doing ugly hacks, such as prefixing the name of the function or class to make the name unique. We also now know how using namespaces can make it much safer to include third party code in large applications without the worry of name collisions.

For more information, pls visit: 

Featured Blog Topics:

No comments :