请看以下示例:
class A implements Serializable {
serialize() {}
}
class B extends A {
serialize() {}
}
A类是每个页面上使用的持久但最小的类. B类是临时管理员(在设置屏幕上使用)类,它通过读取文件来填充成员.
我需要序列化对象并在数据库中存储两次,一次用于常规页面,第二次(有限生命)用于管理页面.
$instance = new B(); // and populate
$data = serialize( $instance );
这将始终调用过度使用的方法.有没有什么方法可以将$instance转换为A类,以便我可以调用A类的序列化方法?
解决方法:
可以通过创建一个闭包,查看以下片段进行演示
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,casting,inheritance
来源: https://codeday.me/bug/20190629/1324008.html