views:

26

answers:

1

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).

+3  A: 

There's no language feature which could give you that behaviour, sounds like you want to emulate something like C++ friend classes?

However, inside the foo() method you could use debug_backtrace to find out who your caller was, and throw an exception if its not want you want!

Paul Dixon
Not a C++ dev, but after reading (briefly) about friend classes, that sounds like exactly the behavior I'm looking for. Depressing that there's no PHP equivalent.
Tim