11

Is there any way to limit the visibility in PHP in the same way as "package" visibility works in Java or at least "friend" visibility in C++? What's the best practice to maintain large OOP project and not to let anyone use any part of code?

I use private and protected visibility as much as I can but sometimes it's not enough. I know about this request: https://bugs.php.net/bug.php?id=55331. Is there any progress in implementing such thing to PHP? Is there any workaround to protect your code (methods, class variables) from being accessed from anywhere?

Pavel S.
  • 11,892
  • 18
  • 75
  • 113
  • Not exactly like packages in Java, but [namespaces](http://php.net/manual/en/language.namespaces.php) will serve for code encapsulation. – Shef Sep 03 '11 at 10:01
  • Could you type a short example, please? – Pavel S. Sep 03 '11 at 10:09
  • Just a thought, if you really needed to you could use `debug_backtrace` [http://php.net/manual/en/function.debug-backtrace.php] to see what code is calling your code. Essentially writing your own runtime access control. Probably more work than it's worth, and the `debug_backtrace` has a performance hit. – CLo Feb 03 '13 at 22:05

2 Answers2

9

Until today there's no language construct to limit the visibility. But you can annotate your class with phpDocumentor's @internal:

The @internal tag can be used as counterpart of the @api tag, indicating that the associated Structural Elements are used purely for the internal workings of this piece of software.

It's up to the API user to follow that suggestion.

jake stayman
  • 1,687
  • 13
  • 22
Markus Malkusch
  • 7,738
  • 2
  • 38
  • 67
3

As stated here:

No. You can set a variable after declaring a namespace, but variables will always exist in the global scope. They are never bound to namespaces. You can deduce that from the absence of any name resolution descriptions in http://www.php.net/manual/en/language.namespaces.faq.php

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Thanks for the answer. Howerver, I'd still like to know some best practices or workarounds to achieve some protection of your code. – Pavel S. Sep 03 '11 at 10:08
  • 1
    I don't see how this answers OP's question. Namespaces have nothing to do with access visibility. – Markus Malkusch Jul 20 '14 at 11:40
  • @Markus I agree that this old answer of mine doesn't explicitly address it, but it says that (contrary to just a variable) everything in any namespace is global, hence that you have no way to hide members using access modifiers like "private" or "protected". – CodeCaster Jul 20 '14 at 11:48