PhP5's OOP is a good thing. Recently, I found some small materials for new users to train and show them to friends. It is also a good thing for foreigners. The example is short. If there is an OOP Foundation, I will check it at a glance.
Understand
1) basic classes and Instances
<?phpclass Animal{var $name;function set_name($text){$this->name = $text;}function get_name(){return $this->name;}}$lion = new Animal;$lion->set_name("Leo");echo "The name of your new lion is ", $lion->name, ".";?>
2) add some access controllers, such as private
<?phpclass Animal{private $name;function set_name($text){$this->name = $text;}function get_name(){return $this->name;}}$lion = new Animal;$lion->set_name("Leo");echo "The name of your new lion is ", $lion->name, ".";?>
Because privae is used, an error occurs. Use get_name to access
3) constructor
<? Phpclass animal {var $ name; function _ construct ($ text) {$ this-> name = $ text;} function set_name ($ text) {$ this-> name = $ text;} function get_name () {return $ this-> name ;}}$ lion = new animal ("Leo "); echo "the name of your new Lion is", $ lion-> get_name (),". ";?> Use _ construct () as the constructor (note that two followed _)
4. Use inheritance
<?phpclass Animal{var $name;function set_name($text){$this->name = $text;}function get_name(){return $this->name;}}class Lion extends Animal{var $name;function roar(){echo $this->name, " is roaring!<BR>";}}echo "Creating your new lion...<BR>";$lion = new Lion;$lion->set_name("Leo");$lion->roar();?>
5 Overriding
<?phpclass animal{var $name;function set_name($text){$this->name = $text;}function get_name(){return $this->name;}}class Lion extends Animal{var $name;function roar(){echo $this->name, " is roaring!<BR>";}function set_name($text){$this->name = strtoupper($text);}}echo "Creating your new lion...<BR>";$lion = new Lion;$lion->set_name("Leo");$lion->roar();?>
Output: Leo is roaring
The subclass overwrites the set_name method of the parent class.
6. Access the override method in the parent class
<?phpclass Animal{var $name;function set_name($text){$this->name = $text;}function get_name(){return $this->name;}}class Lion extends Animal{var $name;function roar(){echo $this->name, " is roaring!<BR>";}function set_name($text){Animal::set_name($text);}}echo "Creating your new lion...<BR>";$lion = new Lion;$lion->set_name("Leo");$lion->roar();?>