Can a PHP object respond to an undefined method?
Posted
by Nathan Long
on Stack Overflow
See other posts from Stack Overflow
or by Nathan Long
Published on 2010-04-14T14:55:12Z
Indexed on
2010/04/14
21:03 UTC
Read the original article
Hit count: 203
Rails relies on some of the neat aspects of Ruby. One of those is the ability to respond to an undefined method.
Consider a relationship between Dog
and Owner.
Owner has_many :dogs
and Dog belongs_to :owner
.
If you go into script/console
, get a dog object with fido = Dog.find(1)
, and look at that object, you won't see a method or attribute called Owner.
What you will see is an owner_id
. And if you ask for fido.owner
, the object will do something like this (at least, this is how it appears to me):
- I'm being asked for my
.owner
attribute. I don't have one of those! - Before I throw a
NoMethodError
, do I have a rule about how to deal with this? - Yes, I do: I should check and see if I have an
owner_id
. - I do! OK, then I'll do a join and return that owner object.
PHP's documentation is - ahem - a bit lacking sometimes, so I wonder if anyone here knows the answer to this: Can I define similar behavior for objects in PHP? If not, do you know of a workaround for flexible model joins like these?
© Stack Overflow or respective owner