PHP: Protect an object property without knowing its name in advance

seanthurston

New Member
Ok, this may be impossible, but I thought I'd ask before I rework the whole thing... I have a situation like this:I have an object class that can receive "pieces," which are also objects. It works basically like this:\[code\]class myObject { //Receives an associative array of "Piece" objects function __construct($objects) { foreach( $objects as $k=>$v ) { $this->{$k} = $v; }\[/code\]I'm omitting a lot of code obviously, but I hope this gives you the idea. Basically I have a ton of different "piece" objects that do different things, and if I pass an array of them into "myObject" then "myObject" becomes a very flexible and useful class for doing all kinds of different things.So, I could use this to create a "Book" object and have pieces that included a "Author Piece" and an "ISBN Piece", and those pieces would know how to validate data etc. So I might have "$book" with objects set to the member variables "author" and "isbn."This is great because I can do things like:\[code\]echo $book->author; //all Pieces have a __toString() method.echo $book->author->firstName;$book->author->showBio();$book->author->contactForm();\[/code\]...and so on.Now to the point. This system works great, and one of the things that makes it great is that I can pick and choose any of these pieces that I like and stick them into an object to bind them together.But the problem is, I don't want someone else who might use the code later to try:\[code\]$book->author = "John Doe";\[/code\]...because then they'd just have a value instead of the author object. I'd like that to give them an error and instruct them to do this instead:\[code\]$book->author->setName("John Doe");\[/code\]So because I don't know in advance what pieces might be in any individual object (and the entire point is to be able to have the freedom to instantly assemble any kind of object), I can't just set "private $author" in the class declaration.I tried fooling around with __get() and __set() a bit, but I couldn't get it to work without compromising the functionality of the objects as they are now.So, like I said, I know this may be impossible, but before I give up, I thought I'd ask. Is there a way to protect the a property of an object after it has been created without declaring it in the class definition?
 
Back
Top