Check for Function and Class Existence Using PHP

By  on  

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.

Recent Features

  • By
    How to Create a RetroPie on Raspberry Pi – Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

Incredible Demos

  • By
    Spyjax:  Ajax For Evil Using Dojo

    The idea of Spyjax is nothing new. In pasts posts I've covered how you can spy on your user's history with both MooTools and jQuery. Today we'll cover how to check user history using the Dojo Toolkit. The HTML For the sake of this...

  • By
    Fancy Navigation with MooTools JavaScript

    Navigation menus are traditionally boring, right? Most of the time the navigation menu consists of some imagery with a corresponding mouseover image. Where's the originality? I've created a fancy navigation menu that highlights navigation items and creates a chain effect. The XHTML Just some simple...

Discussion

  1. 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.

  2. Thanks for this cool idea. Sometime it really becomes hard to follow other developers of the team, so this idea will really help.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!