Home > Backend Development > PHP Problem > How to call private method of class in php

How to call private method of class in php

王林
Release: 2023-03-12 09:28:02
Original
3092 people have browsed it

The specific steps for calling the private method of a class in PHP: 1. Reflect through the class name; 2. Instantiate through the reflection class; 3. Get the specified method through the method name; 4. Set accessibility; 5. Execution method.

How to call private method of class in php

The operating environment of this article: windows10 system, php 7.1, thinkpad t480 computer.

How should we call the private method of a class in php? We know that there is a complete reflection API in PHP, and the ability to reverse engineer classes, interfaces, functions, methods and extensions has been added. Then we can call and execute private methods in a class through reflection.

Next let’s take a look at the specific code implementation.

Code implementation:

<?php
 
//MyClass这个类中包含了一个名为myFun的私有方法
class MyClass {
    
    private $tmp = &#39;hello&#39;;
    
    private function myFun()
    {
        echo $this->tmp . &#39; &#39; . &#39;world!&#39;;
    }
}
 
//通过类名MyClass进行反射
$ref_class = new ReflectionClass(&#39;MyClass&#39;);
 
//通过反射类进行实例化
$instance  = $ref_class->newInstance();
 
//通过方法名myFun获取指定方法
$method = $ref_class->getmethod(&#39;myFun&#39;);
 
//设置可访问性
$method->setAccessible(true);
 
//执行方法
$method->invoke($instance);
?>
Copy after login

The above is all the implementation code. Friends can execute the above code locally.

If you are very interested in PHP courses, or want to improve your programming skills, you are welcome to join the 17th php training class on the php Chinese website.

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

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