Created
February 12, 2013 15:26
-
-
Save samcrosoft/4770639 to your computer and use it in GitHub Desktop.
This gist is about how to test for class constants defined inside a class from within the class
or outside the class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* THIS GIST IS ABOUT HOW TO TEST FOR CLASS CONSTANTS IN PHP INSIDE AND OUTSIDE THE CLASS | |
* @author Adebola Samuel Olowofela <samcrosoft@gmail.com> | |
* @link https://github.com/samcrosoft | |
* @class SampleClass | |
*/ | |
class SampleClass | |
{ | |
const CONST1 = 1; | |
const CONST2 = "two"; | |
const CONST3 = "three"; | |
/** | |
* This method returns a class constant if it exists | |
* @param string $sConstantName | |
* @return mixed|null | |
*/ | |
public function getClassConstantVariable($sConstantName = "") | |
{ | |
if($this->testIfClassConstantExists($sConstantName) === true) | |
{ | |
// note : you can use self:: instead of static:: | |
return constant("static::$sConstantName"); | |
} | |
else | |
{ | |
// note you can decide to throw an error here and return false or any other value | |
// i have decided to return null | |
return null; | |
} | |
} | |
/** | |
* This method tests if a class constant exists or not | |
* @param string $sConstantName | |
* @return bool | |
*/ | |
private function testIfClassConstantExists($sConstantName = "") | |
{ | |
$bExists = false; | |
if(!empty($sConstantName) && is_string($sConstantName)) | |
{ | |
// note : you can use self:: instead of static:: | |
$bExists = defined("static::$sConstantName") ? true : false; | |
} | |
return $bExists; | |
} | |
} | |
// IDEA 1: TESTING FOR A CLASS CONSTANT OUTSIDE THE CLASS | |
//to test if the class "SampleClass" has a class constant declared or not | |
if(defined('SampleClass::CONST1')) | |
{ | |
//defined | |
// perform action for defined | |
} | |
else | |
{ | |
//not defined | |
// perform not defined action | |
} | |
// IDEA 2 : Using Object Oriented Approach | |
// TESTING USING THE OBJECT ORIENTED APPROACH | |
// testing using the sample class | |
$oSampleClass = new SampleClass(); | |
print $oSampleClass->getClassConstantVariable("CONST1"). "\n"; // should print 1 | |
print $oSampleClass->getClassConstantVariable("CONST2"). "\n"; // should print two | |
var_dump($oSampleClass->getClassConstantVariable("CONST10")); // should display null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment