Hi list!

Don't know if this already exists, but maybe we could consider
brainstorming or gather alternatives for different types of
encapsulation when using composition? Currently, encapsulation like
private and protected is only possible when using inheritance - when
using composition, that is, class A is using (aggregating) class B,
your only alternative is public, so full visibility (or
getters/setters, which also is full visibility, since you can't limit
who's using those methods).

There are four alternatives at least:

* Friend classes, like in C++: Class B is annotated to be a friend of
A, so class A can see the content of class B but no other class can.
* Package private, like in Java: Class A and B are defined in the same
package, so they can see each other's fields that are defined as
"internal"
* Namespace private: Class A and B are defined in the same namespace,
so they can see each other's properties that are defined as "internal"
* Attribute for namespace private: Like above, but not possible right
now since it requires that namespace is added to the PHP runtime

Functionality like this should not be handled by static analysis,
because library authors need to be able to trust it. Psalm supports
already @internal and @psalm-internal, but of course not everyone is
using Psalm/Phpstan/other analyzer.

The problem with package private is that PHP does not have packages.

The problem with namespace private is that it cannot handle namespace
siblings. Another problem is that it can be "hacked" by client code if
the client code decides to use another vendor's namespace (a weird
thing to do, though).

The run-time hit should not be bigger, since we're already checking
each object property for private. Correct me if I'm wrong.

The risk/benefit/effort should be considered for all alternatives. I'd
argue that something is better than nothing, so far as it does not
block future work. :) Maybe adding namespaces to runtime could be a
first step?

Olle

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to