普通网友 2013-12-14 14:53
浏览 6
已采纳

如何从课外调用父方法?

Take the following example:

class A implements Serializable {
    serialize() {}
}
class B extends A {
    serialize() {}
}

Class A is a persistant but minimal class used on every page. class B is temporary admin only (used on a settings screen) class which populates members by reading files.

I need to serialize the object and store in the database twice, once for regular pages, and the second (with a limited life) for the admin page.

$instance = new B(); // and populate
$data = serialize( $instance );

This will always call the over-ridden method. Is there any way I could cast $instance to type A so that I can call on class A's serialize method?

  • 写回答

2条回答 默认 最新

  • duanlujiaji10335 2018-12-11 08:27
    关注

    It's possible by creating a closure, Looks following snippet for demonstration

    <?php
    
    interface Greeting
    {
        public function hello();
    }
    
    class A implements Greeting
    {
        public function hello()
        {
            echo "Say hello from A
    ";
        }
    }
    
    class B extends A
    {
        public function hello()
        {
            echo "Say hello from B
    ";
        }
    }
    
    $b = new B();
    
    $closure = function() {
        return parent::hello();
    };
    
    $closure = $closure->bindTo($b, 'B');
    $closure(); // Say hello from A
    $b->hello(); // Say hello from B
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号