myMethod();```In this example, first define A class named `MyClass`, where"/> myMethod();```In this example, first define A class named `MyClass`, where">

Home  >  Article  >  Backend Development  >  How to call internal methods in php class

How to call internal methods in php class

王林
王林Original
2023-05-06 11:36:06543browse

To call an internal method in a PHP class, you need to instantiate the class first.

Example:

class MyClass {

    public function myMethod() {
        echo "Hello World!";
    }
}

$obj = new MyClass();
$obj->myMethod();

In this example, a class named MyClass is first defined, which contains a class named myMethod() public methods. The next line of code creates an instance of the MyClass object named $obj. The last line of code calls the internal method myMethod() of the $obj object and outputs the string "Hello World!".

With this simple example, you can see how to call internal methods in PHP classes. First create an instance of the class and then call the method using the object operator ->.

It is also worth noting that methods in a class can be public, private or protected. Public methods can be accessed from inside and outside the class, while private and protected methods can only be accessed from within the class.

The following is an example of a class containing private methods:

class MyClass {
    
    private function myPrivateMethod() {
        echo "This is a private method.";
    }

    public function myPublicMethod() {
        echo "This is a public method.";
        $this->myPrivateMethod();
    }
}

$obj = new MyClass();
$obj->myPublicMethod();

In this example, the class MyClass is defined to contain two methods: one named A private method named myPrivateMethod() and a public method named myPublicMethod().

Since myPrivateMethod() is a private method, it can only be used inside the method of the MyClass class. In the public method myPublicMethod(), the string "This is a public method." is first output, and then other internal myPrivateMethod(() is called through the $this operator. ).

That’s some basics of how to call internal methods in PHP classes. Remember, if you want to use methods in a class, you must first instantiate the class. Additionally, public methods can be accessed both internally and externally, while private and protected methods can only be accessed within the class.

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

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