PHP equivalent of friend or internal

前端 未结 4 1315
野的像风
野的像风 2020-12-01 07:21

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 st

4条回答
  •  爱一瞬间的悲伤
    2020-12-01 08:21

    It is also possible to elevate privileges, aka leaking data selectively, using a handshake and closures in php >=5.3.3.

    Basically, the interaction goes: class A has a public method which accepts a class B object, and calls B->grantAccess (or whatever your interface defines), passing it a closure. The closure use($that,$anythingelseyouneed) where $that=$this, and anything else you need to determine what properties are allowed to be accessed. The closure has one argument - the property to return; if it is a property on $that and everything is cool, the closure returns the property. Otherwise, it returns '', or throws an exception, or maybe a default value.

    Class B->grantAccess accepts a callable and stores it, using it in other methods to pluck out private properties the closure allows to be leaked. Make class B's default constructor private. Construct a B using a static factory method that takes a Class A argument, to ensure the handshake happens.

    Gist here: https://gist.github.com/mcamiano/00592fb400e5043d8acd

提交回复
热议问题