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.
Two years ago I documented my struggles with Imposter Syndrome and the response was immense. I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions. I've even caught myself reading the post...
Kids these days, I tell ya. All they care about is the technology. The video games. The bottled water. Oh, and the texting, always the texting. Back in my day, all we had was...OK, I had all of these things too. But I still don't get...
It's best practice to provide an indicator of some sort when performing an AJAX request or processing that takes place in the background. Since the dawn of AJAX, we've been using colorful spinners and imagery as indicators. While I enjoy those images, I am...
Whenever you have a long page worth of content, you generally want to add a "top" anchor link at the bottom of the page so that your user doesn't have to scroll forever to get to the top. The only problem with this method is...
It seems a little redundant to check for class existence when you’re trying to create a new class. If the class does exist, then you want yours to be named something else so that it can be used. I would personally want an error in the example above, so I knew to rename the class.
It would make sense to check for the class before instantiating it, but to check for the class before creating it, seems like it could create some confusing situations.
Thanks for this cool idea. Sometime it really becomes hard to follow other developers of the team, so this idea will really help.