php通过反射访问私有方法

public 修饰的属性和方法所有地方可见,不管是当前类、子类还是类之外。 protected 修饰的属性和方法在当前类和子类中可见。 private 修饰的属性和方法仅在当前类可见。

反射

不过,依然可以通过反射的方式访问私有方法

<?php
class HelloWorld {
	protected $age=20;
    private function sayHelloTo($name) {
        return 'Hello ' . $name."\n\r age:".$this->age;
    }

}

$reflectionMethod = new ReflectionMethod(HelloWorld::class, 'sayHelloTo');
//修改对象的可访问性
$reflectionMethod->setAccessible(true);
//调用指定实例的方法,并且传送参数
echo $reflectionMethod->invoke(new HelloWorld(), 'chen')."\n\r";

//结果
Hello chen
 age:20
 


------------
详见:https://www.cnblogs.com/youyoui/p/7300340.html

更多反射的细节可以参考 PHP 官方文档:https://www.php.net/manual/zh/book.reflection.php 
?>

zed
请先登录后发表评论
  • latest comments
  • 总共0条评论