Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 9 of 9
  1. #1
    Regular Coder mlse's Avatar
    Join Date
    Mar 2005
    Posts
    624
    Thanks
    20
    Thanked 19 Times in 18 Posts

    Overloading "[]"

    I wonder if there are plans to support overloading of "[]" in future releases of PHP .... (I was just thinking about how neat that would be!).

    I know you can kind of do it using __get and __set, but it would be nice to be able to do something like:

    PHP Code:
    class myclass
    {
      public function& 
    __overload_array_operator($index)
      {
        
    //do whatever.
        
    return &$retval;
      }

    Then you could do stuff like:

    PHP Code:
    $instance = new myclass;

    $instance["fruit"] = "banana";

    echo 
    $instance["fruit"];  //Which might print "My fruit is a banana". 
    In the words of Borat; "Eet ees Niiiice!! I like!"

  • #2
    Regular Coder
    Join Date
    Jun 2004
    Posts
    565
    Thanks
    0
    Thanked 18 Times in 18 Posts
    You can do that already. See the SPL manual, esp. ArrayObject.

    You can also implement iteration protocols for your object (other than the default "iterate over all properties") with ArrayIterator to make your object behaviour closer to real arrays.

    dumpfi
    "Failure is not an option. It comes bundled with the software."
    ....../)/)..(\__/).(\(\................../)_/)......
    .....(-.-).(='.'=).(-.-)................(o.O)...../<)
    ....(.).(.)("}_("}(.)(.)...............(.)_(.))Ż/.
    ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
    Little did the bunnies suspect that one of them was a psychotic mass murderer with a 6 ft. axe.

  • #3
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by mlse View Post
    I wonder if there are plans to support overloading of "[]" in future releases of PHP .... (I was just thinking about how neat that would be!).

    I know you can kind of do it using __get and __set, but it would be nice to be able to do something like:

    PHP Code:
    class myclass
    {
      public function& 
    __overload_array_operator($index)
      {
        
    //do whatever.
        
    return &$retval;
      }

    Then you could do stuff like:

    PHP Code:
    $instance = new myclass;

    $instance["fruit"] = "banana";

    echo 
    $instance["fruit"];  //Which might print "My fruit is a banana". 
    In the words of Borat; "Eet ees Niiiice!! I like!"
    maybe can be done now,
    look over __call and __callStatic, probably something like this:

    PHP Code:
    public function __call($name$param){
        if(
    $name === '[]'){
           
    // code to get something at index $param[0] or maybe full index list????
           // something like a get as $thisobj[6,4,5]
        
    }else{
           
    // call __call($name,$param) for parent class????
        
    }

    http://www.php.net/manual/en/languag...verloading.php

    regards

  • #4
    Regular Coder mlse's Avatar
    Join Date
    Mar 2005
    Posts
    624
    Thanks
    20
    Thanked 19 Times in 18 Posts
    Nice! thanks

  • #5
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Too bad that is the only operator overload in php. T'would be great fun to overload the arithmetic operators and get a buddy to debug it Heh heh.
    What you are looking for is actually an interface called ArrayAccess. Using these types of built in interfaces and objects is the reason why I made my LL, DLL, queues and stacks, and the ArrayAccess has been applied to access within the LL and DLL classes. The functions you overload to handle this behaviour are offsetExists, offsetSet, offsetGet and offsetUnset if I'm not mistaken. I have yet to find the actual documentation on the ArrayAccess interface, but you can check the manual for ArrayObject which does implement the ArrayAccess or reflect the ArrayAccess interface.
    I'll note that these can only be used on custom objects that extend either ArrayObject or implement ArrayAccess. Since you are looking at just using it as an accessor to you're object, ArrayAccess interface makes more sense than ArrayObject - there is really no reason to iterate over known properties of an object.

    Edit:
    Oh yes, I should mention this as well since Oesxyl put the effort into showing you a call base. I cannot find the documentation listing the version required for the ArrayObject object or ArrayAccess interfaces, but methinks its version 5.1. This means if you have 5.0.x, you're only option is to override the __call method as Oesxyl shows.
    Last edited by Fou-Lu; 08-11-2008 at 08:52 PM.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #6
    Regular Coder
    Join Date
    Jun 2004
    Posts
    565
    Thanks
    0
    Thanked 18 Times in 18 Posts
    Quote Originally Posted by Fou-Lu View Post
    I have yet to find the actual documentation on the ArrayAccess interface [...]
    Look here under the section "Array Overloading".

    dumpfi
    "Failure is not an option. It comes bundled with the software."
    ....../)/)..(\__/).(\(\................../)_/)......
    .....(-.-).(='.'=).(-.-)................(o.O)...../<)
    ....(.).(.)("}_("}(.)(.)...............(.)_(.))Ż/.
    ŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻŻ
    Little did the bunnies suspect that one of them was a psychotic mass murderer with a 6 ft. axe.

  • #7
    Regular Coder mlse's Avatar
    Join Date
    Mar 2005
    Posts
    624
    Thanks
    20
    Thanked 19 Times in 18 Posts
    I've written a solution using the __call mechanism, but thanks for the other info! I'll have a look at ArrayAccess, looks most promising

  • #8
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by mlse View Post
    I've written a solution using the __call mechanism, but thanks for the other info! I'll have a look at ArrayAccess, looks most promising
    can you post the code?

    regards

  • #9
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Quote Originally Posted by dumpfi View Post
    Look here under the section "Array Overloading".

    dumpfi
    Lol, I found this last night as well though the spl > introduction page, and was coming to post the same thing :P. You posted it first, so you get credit for it .

    mlse - Definitely look into using the ArrayAccess interface, it really simplifies things. This is especially true if you have a standard mutator (setX) and accessor (getX) functions.
    PHP Code:
    class MyObj implements ArrayAccess
    {
        private 
    $prop;

        public function 
    getProp()
        {
             return 
    $this->prop;
        }
        public function 
    setProp($prop)
        {
            
    //Whatever logic here
            
    $this->prop $prop;
        }

        public function 
    offsetExists($offset)
        {
            
    $class get_class();
            return 
    property_exists($this$offset) && ($this->$offset != null);
        }
        public function 
    offsetGet($offset$value)
        {
           
    $method 'get' $offset;
           if (!
    method_exists($this$method))
           {
                
    trigger_error('Undefined index ' $offset ' in ' __CLASS__);
                return 
    false;
           }
           return 
    call_user_func(array($this$method), $value);
        }

        public function 
    offsetSet($offset$value)
        {
           
    $method 'set' $offset;
           if (!
    method_exists($this$method))
           {
                
    trigger_error('Undefined index ' $offset ' in ' __CLASS__);
                return 
    false;
           }
           return 
    call_user_func(array($this$method), $value);
        }

        public function 
    offsetUnset($offset)
        {
            if (isset(
    $this->$offset))
            {
                
    $this->$offset null;
            }
        }

    Or something like this. I didn't test this so I don't know if it will work. Don't forget that there is a difference in using the ArrayAccess vs __call or other magic methods - MyObj is now a typeof ArrayAccess. This means you can make a comparison between this type and another type of ArrayAccess. Offhand I cannot recall wheather type array is an instanceof arrayaccess or not, but ArrayObject is for sure.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •