Why can't constants be accessed outside the class definition in PHP?
Constants in PHP are scoped to the class in which they are defined. This means that they cannot be accessed outside the class definition directly. To access a constant from outside the class, you can create a public static method in the class that returns the constant value.
class MyClass {
const MY_CONSTANT = 'Hello World';
public static function getConstant() {
return self::MY_CONSTANT;
}
}
echo MyClass::getConstant(); // Output: Hello World
Keywords
Related Questions
- What are some common issues when integrating PHP code within layers on a webpage?
- What are some best practices for extracting and manipulating text from HTML pages using PHP?
- What best practices should be followed when handling file operations in PHP, such as reading user credentials from external files?