Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP5: restrict access to function to certain classes

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

like image 433
Tim Avatar asked Jun 03 '10 14:06

Tim


People also ask

How do I restrict access to PHP?

You should look into PHP sessions. You can set a session variable "isLogged" in that redirection file, and then check in admin. php if that session variable is registered, if not redirect to the login page! Note: session_start(); must be called before the $_SESSION global can be utilised.

How can I access private function in PHP?

php //Accessing private method in php with parameter class Foo { private function validateCardNumber($number) { echo $number; } } $method = new ReflectionMethod('Foo', 'validateCardNumber'); $method->setAccessible(true); echo $method->invoke(new Foo(), '1234-1234-1234'); ?>

How do you call a function outside the class in PHP?

you can use require_once() with exact path of that class after that you should use the object of the included class and function name for calling the function of outer class.

What is private function PHP?

Definition and Usage The private keyword is an access modifier. It marks a property or method as private. Private properties and methods can only be used by the class in which the property or method was defined. Derived classes and outside code cannot use them.


1 Answers

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!

like image 102
Paul Dixon Avatar answered Sep 22 '22 20:09

Paul Dixon