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

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

WBOY
WBOYOriginal
2016-08-08 09:20:561211browse

<?<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>?>

The browser output is as follows:

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

The above introduces an example of understanding PHP object-oriented programming (OOP), including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
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