Tuesday 14 August 2018

Check for Function and Class Existence Using PHP

When you've inherited a big website or you're working on a group website where you don't have quick access to communicate with the other developers, it's important to not assume that a custom function or class name has not already been defined. Here's how you can protect yourself:


The PHP
if(!function_exists('show_article')) {
function show_article($id) {
//code here
}
}

if(!class_exists('my_class')) {
class myclass {
//code here
}
}
Using this type of programming can also protect you in case a file gets accidentally included twice. If a file with a function definition were to be included twice, you'd get an ugly "redefined" error when the function is realistically only in one file.

0 comments:

Post a Comment