Home > Backend Development > PHP Tutorial > An example of understanding PHP object-oriented programming (OOP), object-oriented programming oop_PHP tutorial

An example of understanding PHP object-oriented programming (OOP), object-oriented programming oop_PHP tutorial

WBOY
Release: 2016-07-13 09:46:24
Original
850 people have browsed it

An example of understanding PHP object-oriented programming (OOP), object-oriented programming oop

<?<span>php<br /><br />
    </span><span>class</span><span> Person{<br /><br />        //声明一个新变量公共变量<strong>$name</strong>,可被任何包中的类访问<br />        </span><span>public</span> <span>$name</span><span>;
        </span><span>public</span> <span>$sex</span><span>;
        </span><span>public</span> <span>$age</span><span>;<br /><br />        //声明该类的一个方法
        </span><span>function</span><span> say() {
            </span><span>echo</span> "你好!<br />"<span>;
            </span><span>echo</span> "我的的名字是:" . <span>$this</span> -> name ."<br />"<span>;
            </span><span>echo</span> "我的性别是:" . <span>$this</span> -> sex ."<br />"<span>;
        }
    }
<br />    //声明新的Student类为Person的子类
    </span><span>class</span> Student <span>extends</span><span> Person{
        </span><span>public</span> <span>$school</span><span>;
        </span><span>function</span><span> study() {<br />            //parent:: 可用于调用父类中定义的成员方法。<br />            parent::say();</span><span>echo</span> "我的年龄是:" . <span>$this</span> -> age . "<br />我正在" . <span>$this</span> -> school . "上学。"<span>;
        }
    }
<br />  //只用将P1定义为学生类即可
    </span><span>$p1</span> = <span>new</span><span> Student();<br /><br />    //为P1的name,sex,age,school属性赋值
    </span><span>$p1</span> -> name = "张三"<span>;
    </span><span>$p1</span> -> sex = "男"<span>;
    </span><span>$p1</span> -> age = "18"<span>;
    </span><span>$p1</span> -> school = "某某学校"<span>;
    </span><span>$p1</span> -><span> study();
</span>?>
Copy after login

The browser output is as follows:

Hello!
My name is: Zhang San
My gender is: Male
My age is: 18
I am attending a certain school.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1033244.htmlTechArticleAn example of understanding PHP object-oriented programming (OOP), object-oriented programming oop? php class Person{ //Declaration A new variable public variable $name, accessible by any class in the package public $...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template