PHP5: restrict access to function to certain classes

Posted by Tim on Stack Overflow See other posts from Stack Overflow or by Tim
Published on 2010-06-03T14:20:02Z Indexed on 2010/06/03 14:24 UTC
Read the original article Hit count: 208

Is there a way in PHP5 to only allow a certain class or set of classes to call a particular function? For example, let's say I have three classes ("Foo", "Bar", and "Baz"), all with similarly-named methods, and I want Bar to be able to call Foo::foo() but deny Baz the ability to make that call:

class Foo {
    static function foo() { print "foo"; }
}

class Bar {
    static function bar() { Foo::foo(); print "bar"; } // Should work
}

class Baz {
    static function baz() { Foo::foo; print "baz"; } // Should fail
}

Foo::foo(); // Should also fail

There's not necessarily inheritance between Foo, Bar, and Baz, so the use of protected or similar modifiers won't help; however, the methods aren't necessarily static (I made them so here for the simplicity of the example).

© Stack Overflow or respective owner

Related posts about php

Related posts about object-oriented