PHP friend classes

Projects - Ideas
Print
Read : 24,328 times
(2 votes, average 3.50 out of 5)



This concept is adapted from C++. A 'friend' class can access the 'protected' members of the class in which it is declared as a friend.

Why ?

Unfortunately, there is no clean, easy-to-use and fast solution for this yet, and a lot of projects have asked for such a feature for years. Today, the only alternatives are :

The subject was discussed years ago, and it was decided not to implement 'friend class' declarations (see https://bugs.php.net/bug.php?id=34044). But the discussions occurred ten years ago when the PHP 5 OO system was young. The context is very different now.

The feature

It would be globally similar to C++ friend classes, except that a PHP friend class would have access to protected resources, but not private ones ('private' would remain private).

The inheritance rules would be similar to C++ rules (adapted as C++ friend classes access private resources) :

Example

    class Foo
    {
    friend Bar, Bar2;

    protected static function myfunc() {}
    }

//----------

    class Bar
    {
    Foo::myfunc();    // OK
    }

    class Other
    {
    Foo::myfunc();    // Error
    }

 
Joomla SEO powered by JoomSEF