: This article describes how to learn php policy patterns. This article is based on "in-depth php object-oriented mode and practice". For more information about PHP tutorials, see.
# Strategy mode # define the abstract class Lessonabstract class Lesson {private $ duration; private $ coststrategy; # define the attribute public function _ construct ($ duration, CostStrategy $ strategy) {# upload an object during instantiation # Use the CostStrategy class to process a behavior, instead of calling its own method to process $ this-> duration = $ duration; $ this-> coststrategy = $ strategy;} public function cost () {return $ this-> coststrategy-> cost ($ this );#??? ??? ??? ??? ??? ??? ??? ??? ???} # It is not implemented by using the cost method in the abstract CostStrategy class of the abstract class. # it seems that the output value is used # TimedCostStrategy # the method in FixedCostStrategy. so # When instantiating an object, the # TimedCostStrategy # FixedCostStrategy method is used. public function chargeType () {return $ this-> coststrategy-> chargeType ();} public function getDuration () {return $ this-> duration;} abstract class CostStrategy {# abstract class is abstract function cost (Lesson $ lesson) that cannot be instantiated; # the input parameter is the object abstract function charge Type ();} class TimedCostStrategy extends CostStrategy {public function cost (Lesson $ lesson) {return ($ lesson-> getDuration () * 5); # in the Lesson class, the returned value of getDuration is return $ this-> duration;} public function chargeType () {return 'Hourly rate! ';}} Class FixedCostStrategy extends CostStrategy {function cost (Lesson $ lesson) {return 30; # Here is how to call the method, but simply returns a value} function chargeType () {return 'fixed rate ';}} # inheritance class Lessonclass Lecture extends Lesson {}# inheritance class Lesson class Seminar extends Lesson {}# instantiated object $ lessons [] = new Seminar (4, new TimedCostStrategy ()); # generate a TimeConsTrategy object $ lessons [] = new Lecture (4, new FixedCostStrategy ()); # generate a FixedConsTrategy object # Call the methods const () and chargeType () in TimeConsTrategy & FixedConsTrategy respectively, and traverse foreach ($ lessons as $ lesson) {# print the output print "lesson charge {$ lesson-> cost () }=>>"; print "Charge type: {$ lesson-> chargeType ()}
";}
The above describes how to learn php policy patterns-introduced from "deep php object-oriented mode and practice", including some content, and hope to help those who are interested in PHP tutorials.