Home > Article > Backend Development > Can External Methods Be Included in a PHP Class, and What\'s the Best Alternative?
Can code be included into a PHP class?
Including code directly into the body of a class is not possible in PHP. However, methods can be included from external files outside of the class body.
Segregating Business Logic
The desire to separate business logic from other class elements is understandable. However, including methods from a separate file violates PHP syntax rules.
Performance Concerns
If Myclass.php is included only once per request, the external file Myclass_methods.php will also be included only once. Thus, performance should not be a major concern.
Proper Solution: Strategy Pattern
To dynamically change class behavior, the Strategy Pattern is a more suitable approach than including external files. It involves creating an interface with a defined method and implementing multiple classes that conform to the interface with different implementations of the method.
Implementation:
// MeowingInterface.php interface MeowingInterface { public function meow(): string; } // RegularMeow.php class RegularMeow implements MeowingInterface { public function meow(): string { return 'meow'; } } // LolcatMeow.php class LolcatMeow implements MeowingInterface { public function meow(): string { return 'lolz xD'; } } // Cat.php class Cat { private MeowingInterface $meowingBehaviour; public function setMeowingBehaviour(MeowingInterface $meowingBehaviour): void { $this->meowingBehaviour = $meowingBehaviour; } public function meow(): string { return $this->meowingBehaviour->meow(); } }
Usage:
// index.php require_once 'MeowingInterface.php'; require_once 'RegularMeow.php'; require_once 'LolcatMeow.php'; require_once 'Cat.php'; $cat = new Cat(); $cat->setMeowingBehaviour(new RegularMeow()); echo $cat->meow(); // Outputs "meow" // Change behaviour $cat->setMeowingBehaviour(new LolcatMeow()); echo $cat->meow(); // Outputs "lolz xD"
By following the Strategy Pattern, you can easily change the behavior of a class without resorting to unorthodox practices like including external files. This approach provides code flexibility and maintainability in the long run.
The above is the detailed content of Can External Methods Be Included in a PHP Class, and What\'s the Best Alternative?. For more information, please follow other related articles on the PHP Chinese website!