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).
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.
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'); ?>
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With