举个例子:
class A implements Serializable {
serialize() {}
}
class B extends A {
serialize() {}
}
A 类是在每个页面上使用的持久但最小的类。 B 类是临时管理员(在设置屏幕上使用)类,它通过读取文件来填充成员。
我需要将对象序列化并存储在数据库中两次,一次用于常规页面,第二次(生命周期有限)用于管理页面。
$instance = new B(); // and populate
$data = serialize( $instance );
这将始终调用覆盖的方法。有什么方法可以将 $instance
转换为类型 A
以便我可以调用 class A
的序列化方法?
最佳答案
可以通过创建一个闭包来实现,看下面的代码片段进行演示
<?php
interface Greeting
{
public function hello();
}
class A implements Greeting
{
public function hello()
{
echo "Say hello from A\n";
}
}
class B extends A
{
public function hello()
{
echo "Say hello from B\n";
}
}
$b = new B();
$closure = function() {
return parent::hello();
};
$closure = $closure->bindTo($b, 'B');
$closure(); // Say hello from A
$b->hello(); // Say hello from B
关于php - 如何从类外部调用父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20584723/