Home > php教程 > php手册 > 一个理解PHP面向对象编程(OOP)的实例,面向对象编程oop

一个理解PHP面向对象编程(OOP)的实例,面向对象编程oop

WBOY
Release: 2016-06-13 08:57:52
Original
1628 people have browsed it

一个理解PHP面向对象编程(OOP)的实例,面向对象编程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

 

 

浏览器输出结果如下:

你好!
我的的名字是:张三
我的性别是:男
我的年龄是:18
我正在某某学校上学。

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template