Rumah >pembangunan bahagian belakang >tutorial php >一个理解PHP面向对象编程(OOP)的实例
<span>php<br></span><span>class</span><span> Person{<br> //声明一个新变量公共变量$name,可被任何包中的类访问<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> //声明该类的一个方法 </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> //为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>?>
浏览器输出结果如下:
你好!
我的的名字是:张三
我的性别是:男
我的年龄是:18
我正在某某学校上学。
以上就介绍了一个理解PHP面向对象编程(OOP)的实例,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。