Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call on a parent method from outside the class?

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?

like image 481
Twifty Avatar asked Dec 14 '13 14:12

Twifty


Video Answer


1 Answers

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\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
like image 186
Gasol Avatar answered Oct 23 '22 02:10

Gasol