Tutorial :if i define something in a class, how do i call in within the class?


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.



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.


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;  


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();  


Simply use the name of the constant.


  echo "Root path is " . __ROOT_PATH__;  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »