How can one define a function in PHP that only accepts class constants as parameters?
When defining a function in PHP that only accepts class constants as parameters, you can achieve this by using the `::class` syntax to reference the class constant within the function parameter. This ensures that only valid class constants can be passed as arguments to the function, preventing any other values from being accepted.
class MyClass {
const CONSTANT_1 = 'Value1';
const CONSTANT_2 = 'Value2';
public function myFunction($constant) {
if ($constant === self::class . '::CONSTANT_1' || $constant === self::class . '::CONSTANT_2') {
// Valid class constant passed
// Add your function logic here
} else {
// Invalid class constant passed
throw new InvalidArgumentException('Invalid class constant provided');
}
}
}
// Example usage
$myObject = new MyClass();
$myObject->myFunction(MyClass::class . '::CONSTANT_1');
Keywords
Related Questions
- How can a PHP beginner effectively convert image URLs from a database into actual image outputs on a webpage?
- What are some best practices for automating the deletion of folders in PHP without manual intervention?
- Is it advisable to rely on the __destruct() method for database operations in PHP, or are there better alternatives for handling data updates?