How do I define class constants in php5?

I want to define a constant that is accessible in a class. Such that NewClass::MYCONSTANT will refer to a constant value.

Public Comments

  1. I think you can create a class and define a constant inside the class if you need help how to define constants check the syntax here: http://www.php.net/manual/en/language.constants.php
  2. See the following page on PHP5's "Scope Resolution Operator", there is an example of accessing a class constant on this page. Consider this: <?php class Page { constSITE_NAME = 'My Cool Website'; public$title; function __construct ($title = null) { $this->title = isset($title) ? $title : 'Home'; } function get($var) { return isset($this->$var) ? $this->$var : null; } } ?> ... and the corresponding view: <?php require_once('Page.php'); $page = new Page('Welcome'); ?> <html> <head> <title><?php echo Page::SITE_NAME.' - '.$page->get('title'); ?></title> </head> <body> <?php echo $page->get('title'); ?> </body> </html>
  3. If you're wanting to have a constant (which are global variables) you use: define("RESULTS_PER_PAGE", 10); // which sets the RESULTS_PER_PAGE constant to 10. However, if you're using OO Programming, and you want to refer to a variable, it may just be best to make a public variable - public resultsPerPage; ... function __construct() { ... resultsPerPage = 10; ... } Hope this helps.
Powered by Yahoo! Answers