Twi*_*fty 5 php inheritance casting
举个例子:
class A implements Serializable {
serialize() {}
}
class B extends A {
serialize() {}
}
Run Code Online (Sandbox Code Playgroud)
A 类是每个页面上使用的持久但最小的类。B 类是临时管理员专用(在设置屏幕上使用)类,它通过读取文件来填充成员。
我需要序列化对象并在数据库中存储两次,一次用于常规页面,第二次(寿命有限)用于管理页面。
$instance = new B(); // and populate
$data = serialize( $instance );
Run Code Online (Sandbox Code Playgroud)
这将始终调用重写的方法。有什么方法可以转换$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
Run Code Online (Sandbox Code Playgroud)