A group of friends are playing hide-and-seek games. From time to time, new children join us. How can I know how many people are playing? Please use the object-oriented idea to compileProgramSolution.
There are two ways to solve this problem: using global variables and static variables
<? PHP // A group of friends are playing hide-and-seek games. From time to time, new children join. // how do I know how many people are playing? // Use the object-oriented idea to write programs. /* // One method uses the Global $ global_nums global variable; // declare the global variable first and then assign a value to it $ global_nums = 0; Class child {public $ name; // constructor public function _ construct ($ name) {$ this-> name = $ name;} // defines a method for counting the number of people public function allplay () {// declare the use of the global variable global $ global_nums; $ global_nums + = 1; echo $ this-> name. "join the game. <br/> ";}}$ p1 = new child (" Lily "); $ P1-> allplay (); $ P2 = new child (" Lucy "); $ P2-> allplay (); $ P3 = new child ("kucy"); $ P3-> allplay (); echo $ global_nums; */ // Second, use static variables in the class Class Child { Public $ Name ; // Declare static variables in the class Public Static $ Allplay = 0 ; Public Function _ Construct ( $ Name ){ $ This -> Name = $ Name ;} // Count Public Function Addplay (){ // Use static variables in the class. The following two methods are available in the class to access static variables // self: $ static variable name and Class Name: $ static variable name// Self: $ allplay + = 1; Child :: $ Allplay + = 1 ; Echo $ This -> Name. "join the game. <br/>";}} $ P1 = New Child ("Lily" ); $ P1 -> Addplay (); $ P2 = New Child ("Lucy" ); $ P2 -> Addplay (); $ P3 = New Child ("kucy" ); $ P3 -> Addplay (); $ P4 = New Child ("uucy" ); $ P4 -> Addplay (); // There is only one way to access static variables outside the class: Class Name: $ static variable name Echo Child :: $ Allplay ; ?>