If I have a class that includes a file with a constant like so:
define("FOO", "bar");
Is there a way to make the class include the file with encapsulation so if I use the class somewhere that already has a FOO
constant defined it won't break?
Create a static class and use constants would be the best way to encapsulate specific constants:
static class Constants
{
const Name = 'foo';
const Path = 'Bar';
}
And then use like so:
echo Constants::Name; //foo
echo Constants::Path; //bar
in regards to the precheck you can do
function _defined($key,$check_classes = false)
{
if($check_classes)
{
foreach(get_declared_classes() as $class)
{
if(constant($class . '::' . $key) !== null)
{
return true;
}
}
}
if(!defined($key)) //global Scope
{
return true;
}
}
Usage:
class a
{
const bar = 'foo';
}
if(_defined('bar',true)) //This would be true because its within a
{
//Blah
}
If your thinking of a situation like so
class a
{
const b = '?';
}
class b
{
const b = '?';
}
the constants are within the class scope so they would have no affect on one another !