5

I have a class with an internal array, and I'd like to overload the subscript operator to access the internal array and provide debug/logging actions.

Is there any possible way to overload the [] operator in PHP, or is there another option I should be chasing in this case?

4
  • duplicate of Operator Overloading in PHP Commented Sep 28, 2011 at 16:53
  • @JRL: That is the right question, but the accepted answer is really bad. Please don't dupe on it. Commented Sep 28, 2011 at 16:56
  • why do you call it subscript? Commented Sep 28, 2011 at 17:17
  • It's what is always been called in the languages that I've learned - msdn.microsoft.com/en-us/library/th52k9c8(v=vs.80).aspx Commented Sep 28, 2011 at 19:03

1 Answer 1

7

Yes, with the ArrayAccess interface. Although you won't be able to cast the object to a proper array.

With ArrayObject (as mentioned in the duplicate question) you can however. Also see this comment on php.net on how to achieve this when you are extending ArrayObject.

Sign up to request clarification or add additional context in comments.

5 Comments

I'll give you an upvote if you remove the part about ArrayObject. It's just the wrong approach.
@NikiC: hmmm, I've seen your comment on the other answer now; I hear what you are saying, but I don't necessarily agree with it. I think it depends on what functionality you are looking for. So I agree in part that caution is advised.
What would you suggest fireeyedboy? :) I like to see a few options before selecting if there are any others - though this one looks pretty good so far. :) +1.
@w00te: it really depends on the intended use. What do you want to achieve? Merely subscript overloading, or being able to iterate the object with foreach() as well, casting the object to proper array as well, etc.?
Actually I worked out how to use this - I just had to look at a few more examples. Took me a minute to wrap my head around the ArrayAccess way of doing things - I'm too used to C-like languages :p Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.