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

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

WBOY
WBOYasal
2016-06-13 08:57:521621semak imbas

一个理解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>?>

 

 

浏览器输出结果如下:

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

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn