How can a Closure in PHP access a class constant?
Closures in PHP can access class constants by using the `use` keyword to import the class name and then accessing the constant within the closure. This allows the closure to access the class constant as if it were a variable within its scope.
class MyClass {
const MY_CONSTANT = 'Hello';
public function myClosure() {
$closure = function() {
echo MyClass::MY_CONSTANT;
};
$closure();
}
}
$myClass = new MyClass();
$myClass->myClosure(); // Output: Hello
Keywords
Related Questions
- What considerations should be made when changing the default port for Apache in XAMPP, especially in relation to PHP session management?
- What resources or tutorials would you recommend for a PHP beginner looking to execute SQL queries from user input?
- What are the potential security risks of storing passwords as plain text in a database?