views:

58

answers:

3

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?

A: 

You can use a class contant

class Foo
{
    constant FOO = 'bar'
}

However, you will have to include the class before you can use the constant with Foo::FOO. An alternative with regular constants is to use to prefix them with a vendor prefix to make clashes less likely, e.g.

define('JOHN_FOO', 'bar')

or use the newly introduced namespaces (PHP 5.3)

define('JohnIsaacks\FOO', 'bar');

But in all cases, I wonder why you would need that. If you want to load classes, simply add in an autoloader.

Gordon
or just `require_once`
RobertPitt
@Robert Sure, but that wouldnt help with contant clashing, just with classes of the same name.
Gordon
A: 

You can check if constant already defined using defined:

<?php
define("FOO", "1");
if (!defined("FOO")) { ## check if constant is not defined yet
    define("FOO", "2");
}
echo FOO;
?>
Ivan Nevostruev
+1  A: 

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 !

RobertPitt