Published on 24 March 2011 by @mathiasverraes
In PHP, when a property or method is marked private, it can only be accessed from within that class. That includes other instances of the same class. This may seem counter-intuitive at first, because we are used to dealing with instances of classes. The visibility operator however works not on object-level, but on class level.
This should make it clear that both instances of Foo have access to each other’s private properties.
What practical use does this have? A great candidate for this are Value Objects. If we want to make sure that to separate instances of Foo are actually equal, we can easily compare their private properties:
Nice info, Mathias! It’s very counter-intuitive indeed. On the other OO languages I know of (Delphi, various .NET dialects) a private variable is inaccessible outside the context of the owner object instance.
Good info. Had no idea php worked like this.
Also, great use case….very practical!
This is also the case in Java, which i found rather awkward when i found it.. but apparently it has some use. kind of takes away the principle behind private if you can extend a class to create functions to read another instance of that base class` privates :)
Follow @mathiasverraes on Twitter.
|Advanced Domain-Driven Design||DDD Europe||workshop||Brussels, Paris||2018|
|Design Heuristics||DDD eXchange||keynote||London||April 2018|
|DDD for Messaging Architectures||ExploreDDD||workshop||Denver||Sep 2018|
|Design Heuristics||Kandddinsky||talk||Berlin||Oct 2018|
|Tactical DDD||Kandddinsky||workshop||Berlin||Oct 2018|
This work by Mathias Verraes is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 License.