¿Es posible sobrecargar operadores en PHP?


Específicamente, me gustaría crear una clase Array y me gustaría sobrecargar el operador [].

Author: systemovich, 2009-04-25

6 answers

Si está utilizando PHP5 (y debería serlo), eche un vistazo a las clases SPL ArrayObject. La documentación no es demasiado buena, pero creo que si extiende ArrayObject, tendría su matriz "falsa".

EDITAR: Aquí está mi ejemplo rápido; Me temo que no tengo un caso de uso valioso:

class a extends ArrayObject {
    public function offsetSet($i, $v) {
        echo 'appending ' . $v;
        parent::offsetSet($i, $v);
    }
}

$a = new a;
$a[] = 1;
 50
Author: cbeer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-16 05:23:36

En realidad, la solución óptima es implementar los cuatro métodos de la interfaz ArrayAccess: http://php.net/manual/en/class.arrayaccess.php

Si también desea usar su objeto en el contexto de 'foreach', tendría que implementar la interfaz' Iterator': http://www.php.net/manual/en/class.iterator.php

 24
Author: panicz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-15 09:06:42

El concepto de sobrecarga y operadores de PHP (ver Sobrecarga, y Operadores de matriz) no es como el concepto de C++. No creo que sea posible sobrecargar operadores como+, -, [], etc.

Posibles Soluciones

 20
Author: grammar31,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:46:54

Para una solución simple y limpia en PHP 5.0+, necesita implementar el ArrayAccess interfaz y funciones de anulación offsetGet, offsetSet, offsetExists y offsetUnset. Ahora puede usar el objeto como una matriz.

Ejemplo:

<?php
class A implements ArrayAccess {
    private $data = array();

    public function offsetGet($offset) {
        return isset($this->data[$offset]) ? $this->data[$offset] : null;
    }

    public function offsetSet($offset, $value) {
        if ($offset === null) {
            $this->data[] = $value;
        } else {
            $this->data[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->data[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->data[$offset]);
    }
}

$obj = new A;
$obj[] = 'a';
$obj['k'] = 'b';
echo $obj[0], $obj['k']; // print "ab"
 8
Author: Fabien Sa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-03 09:09:19

No parece ser una característica del lenguaje, vea este error . Sin embargo, parece que hay un paquete que le permite hacer algún tipo de sobrecarga.

 2
Author: Benson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-24 22:02:16

En pocas palabras, no; y sugeriría que si cree que necesita una sobrecarga al estilo C++, es posible que deba reconsiderar la solución a su problema. O tal vez considere no usar PHP.

Parafraseando a Jamie Zawinski, "Tienes un problema y piensas,' ¡Lo sé! ¡Usaré la sobrecarga del operador! Ahora tienes dos problemas."

 0
Author: dirtside,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-25 02:45:54