tags:

views:

495

answers:

2

Is there some equivalent of "friend" or "internal" in php? If not, is there any pattern to follow to achieve this behavior?

Edit: Sorry, but standard Php isn't what I'm looking for. I'm looking for something along the lines of what ringmaster did.

I have classes which are doing C-style system calls on the back end and the juggling has started to become cumbersome. I have functions in object A which take in object B as a parameter and have to call a method in object B passing in itself as an argument. The end user could call the method in B and the system would fall apart.

A: 

I'm pretty sure what you're looking for is "protected" or "private", depending on your use case.

If you're defining an function in a class, and you only want it available to itself, you'll define it this way:

private function foo($arg1, $arg2) { /*function stuff goes here */ }

If you're defining a function in a class that you want to be available to classes which inherit from this class, but not available publicly, definite it this way:

protected function foo($arg1, $arg2)

I'm pretty sure that by default in PHP5, functions are public, meaning you don't have to use the following syntax, but it's optional:

public function foo($arg1, $arg2) { /*function stuff goes here */ }

You'll still have to instantiate the object before using a public function. So I'll just be thorough and let you know that in order to use a function in a class without instantiating an object, be sure to use the following syntax:

static function foo($arg1, $arg2) { /*function stuff goes here */ }

That will allow you to use the function by only referencing the class, as follows:

MyClass::foo($a1, $a2);

Otherwise, you'll need to do the following:

$myObject = new MyClass();
$myObject->foo($a1, $a2);
Robert Elwell
+3  A: 

PHP doesn't support any friend-like declarations. It's possible to simulate this using the PHP5 __get and __set methods and inspecting a backtrace for only the allowed friend classes, although the code to do it is kind of clumsy.

Here's some sample code and discussion on the topic.

ringmaster
This is a lovely hack! I love it and am repulsed by it. Clever though. +1
Allain Lalonde
What's the performance like with this? Is it a noticeable hit? This would actually be exactly what I'm looking for.
smack0007