How to access parent class method in php

王林
Release: 2023-03-06 18:26:02
Original
3036 people have browsed it

How to access parent class methods in php: You can use [$this->method name();] to access. If there is this method in the subclass, the method in the subclass is accessed. If If there is no such method in the subclass, access the method in the parent class.

How to access parent class method in php

Method call:

$this->Method name(); If there is this method in the subclass, the subclass is called If there is no method in the class, the method in the parent class will be called.

parent::The method in the parent class is always called.

(Recommended tutorial: php video tutorial)

Variable calling: $this->variable name; if there is this variable in the subclass, the subclass is called in the class, if not, the

code implementation in the parent class is called:

<?php
class A{
    public $a1=&#39;a1&#39;;
    protected $a2=&#39;a2&#39;;
    function test(){
           echo "hello!<hr/>";
    }
}
class B extends A{//若A类和B类不在同一文件中 请包含后(include)再操作
    public $a1=&#39;b1&#39;;
    function test2(){
            $this->test();
              parent::test();//子类调用父类方法
    }
    function test()
    {   
        echo $this->a1.&#39;,&#39;;
        echo $this->a2.&#39;,&#39;;
        echo "b2_test_hello<hr/>";
    }
}
$a = new B();
$a->test();//b1,a2,b2_test_hello
$a->test2();//b1,a2,b2_test_hello//hello!
Copy after login

Related recommendations: php training

The above is the detailed content of How to access parent class method in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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