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.
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 = 'hello'; private function myFun() { echo $this->tmp . ' ' . 'world!'; } } //通过类名MyClass进行反射 $ref_class = new ReflectionClass('MyClass'); //通过反射类进行实例化 $instance = $ref_class->newInstance(); //通过方法名myFun获取指定方法 $method = $ref_class->getmethod('myFun'); //设置可访问性 $method->setAccessible(true); //执行方法 $method->invoke($instance); ?>
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!