Simple examples of PHP object-oriented programming class definition and usage, php Object-Oriented Programming
This document describes the definition and usage of PHP object-oriented programming classes. We will share this with you for your reference. The details are as follows:
<? Phpclass Person {private $ name; private $ sex; private $ age; function _ construct ($ name = "", $ sex = "male", $ age = 22) {$ this-> name = $ name; $ this-> sex = $ sex; $ this-> age = $ age;} // It is automatically called when values are directly assigned to a private property, some invalid values can be blocked. // some versions earlier can be set to private function _ set () // The magic method _ set () must have public visibility // because 5.35 imposes strict restrictions on the magic method, public function _ set ($ propertyName, $ propertyValue) {if ($ propertyName = "Sex") {if (! ($ PropertyValue = "male" | $ propertyValue = "female") {return;} if ($ propertyValue> 150 | $ propertyValue <0) {return ;}} // assign the corresponding value $ this-> $ propertyName = $ propertyValue Based on the passed member attribute name ;} // obtain the private property public function _ get ($ propertyName) {if (isset ($ this-> $ propertyName) {return ($ this-> $ propertyName );} else {return (NULL) ;}} public function _ isset ($ propertyName) {if ($ propertyName = "nam E ") {return false; // return false. this attribute cannot be determined outside the object} return isset ($ this-> $ propertyName );} public function _ unset ($ propertyName) {if ($ propertyName = "name") {return; // The name attribute cannot be deleted} unset ($ this-> $ propertyName);} function say () {echo $ this-> name. "Talking <br/>";} function run () {echo "Walking · <br/>";} function _ destruct () {echo "goodbye ". $ this-> name. "<br/>" ;}}$ person1 = new Person (); $ person2 = ne W Person ("2"); $ person3 = new Person ("3"); // automatically calls _ set () $ person1-> name = "James "; echo $ person1-> name; echo "<br/>"; echo $ person1-> say (); // automatically calls _ get () echo $ person1-> age; echo "<br/>"; var_dump (isset ($ person1-> name); echo "<br/> "; unset ($ person1-> name); echo "unset ------------> ". $ person1-> name; // name is not unset () echo "<br/>"; $ person2 = null;?>
Result:
Zhang San is talking about 22 bool (false) unset ------------> Zhang San goodbye2goodbye3goodbye Zhang San