php调取私有类方法
场景: 覆写父类的某个protected方法比如m1,m1里又调取1个父类的private方法,不想复制粘贴这个方法,就需要能直接调用这个private方法了
P1.php
<?php
class P1
{
private function name()
{
return "p1-name";
}
}
S1.php
<?php
class S1 extends P1
{
public function intro(){
// 无法调用
// return $this->name();
return $this->callParentPrivateMethod("name");
}
/**
* 获取父类私有方法的反射对象
*/
private function getParentPrivateMethod($methodName)
{
$reflection = new \ReflectionClass(get_parent_class($this));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method;
}
/**
* 调用父类的私有方法
*/
private function callParentPrivateMethod($methodName, ...$args)
{
$method = $this->getParentPrivateMethod($methodName);
return $method->invoke($this, ...$args);
}
}
index.php
<?php
error_reporting(E_ALL);
ini_set("display_errors","On");
restore_exception_handler();
restore_error_handler();
require_once "P1.php";
require_once "S1.php";
$obj=new S1();
var_dump($obj->intro());

浙公网安备 33010602011771号