3

I need some classes to befriend other classes in my system. Lack of this feature made me publicize some methods which shouldn't be public. The consequences of that are that members of my team implement code in a bad and ugly way which causes a mess.

Is there a way to define a friendship in php 5.3?

(I am aware of http://bugs.php.net/bug.php?id=34044 You might want to vote there if there is no simple solution).

Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278

3 Answers3

3

I was seeking the same functionality and was able to implement a solution. To use it, just derive from class Friendship and specify the classes that are friends of your derived class. You can find it here: http://rommelsantor.com/clog/2011/04/23/php-5-3-class-friendship-support

R. S.
  • 31
  • 3
0

In short, no. The generally accepted approach is to either educate your team on how to develop against your libraries or redesign. The first solution can be done quite easily by building docs with phpdoc and setting the visibility in the docbloc comments with @visibility, and of course actually documenting the classes. The second I wouldn't be able to comment on without knowing a little more detail.

/**
 * Some helper class for LibraryInterface
 *
 * ATTENTION!
 * This class should not be used outside this package.
 *
 * @visibility package
 * @package mypackage
 */
class Helper
{
  public function doStuff()
  {
    /* does stuff */
  }
}

/**
 * Class for accessing some part of the library.
 *
 * @visibility public
 * @package mypackage
 */
class LibraryInterface
{
  public function doStuff()
  {
    $this->helper->doStuff();
  }
}
Rob Young
  • 1,235
  • 11
  • 19
  • Educating people is not as easy as you think (and/or I am not that talented at educating).Besides, "educating" team members on how to use your code is one of the major reasons we have access levels to members IMHO. – Itay Moav -Malimovka May 30 '10 at 17:28
-1

I'm not sure what you mean by "befriend". You can use abstract classes, in which any new class can "implement" that class. Or you can have classes extend other classes and make the methods, variables, etc "protected" as opposed to public or private.

If your team implements any code "in a bad and ugly way", then you may have bigger problems.

Brent Baisley
  • 12,641
  • 2
  • 26
  • 39
  • 1
    In e.g. C++ a class can mark non-member functions/classes as friends, granting them the same access as members of that class (i.e. friend functions/methods have access to protected/private members of the class). – VolkerK May 30 '10 at 14:25
  • I am sorry, but you completely missed my question.In full OOP "Friend" is an access level, like public,protected,private not some kind of abstract/design pattern. – Itay Moav -Malimovka May 30 '10 at 14:38
  • completely missed!? You yourself just said "friend" is like public, protected, private, which I mentioned in my answer. PHP != Full OOP – Brent Baisley May 31 '10 at 02:32