tags:

views:

138

answers:

3

i have something like

 define("__ROOT_PATH__", "http://{$_SERVER['HTTP_HOST']}/admin");

within a class. how do i call it from within functions is it with a cologn? i tried looking it up on google but nothing.

thanks

A: 

Simply use the name of the constant.

i.e.

  echo "Root path is " . __ROOT_PATH__;
Zoomzoom83
+11  A: 

The function define() is intended for global constants, so you just use the string __ROOT_PATH__ (I would recommend using another naming scheme, though. Constants starting with two underscores are reserved by PHP for their magic constants)

define('__ROOT_PATH__', 'Constant String');
echo __ROOT_PATH__;

If you want to declare a class constant, use the const keyword:

class Test {
    const ROOT_PATH = 'Constant string';
}
echo Test::ROOT_PATH;

There is one problem though: The class constants are evaluated while your script is being parsed, so you cannot use other variables within these constants (so your example will not work). Using define() works, as it is treated like any other function and the constant value can be defined dynamically.

EDIT:

As PCheese pointed out, you can access class constants using the keyword self, instead of the class name from within the class:

class Test {
    const ROOT_PATH = 'Constant string';
    public function foo() {
        echo self::ROOT_PATH;
    }
}
# You must use the class' name outside its scope:
echo Test::ROOT_PATH;
soulmerge
I think I like your answer better, it's more concise: I would simply add that within a function of the Test class, you can refer to constants with `self::ROOT_PATH`
PCheese
Thx, added to answer
soulmerge
+3  A: 

Using define will define the constant globally, so just refer to it directly in your code:

echo __ROOT_PATH__;

If you want to scope a constant to a class, you need to declare it differently. However, this syntax will not let you declare it dynamically as you did above, using $_SERVER.

<?php
class MyClass {
    const MY_CONST = "foo";
    public function showConstant() {
        echo self::MY_CONST;
    }
}

// Example:
echo MyClass::MY_CONST;
$c = new MyClass();
$c->showConstant();
PCheese