función estática de php


Tengo una pregunta con respecto a la función estática en php.

Supongamos que tengo una clase

class test {
    public function sayHi() {
        echo 'hi';
    }
}

Si lo hago test::sayHi(); funciona sin problemas.

class test {
    public static function sayHi() {
        echo 'hi';
    }
}

test::sayHi(); funciona también.

¿Cuáles son las diferencias entre primera y segunda clase?

¿Qué tiene de especial una función estática?

Author: Prof. Falken, 2009-05-24

6 answers

En la primera clase, sayHi() es en realidad un método de instancia que está llamando como un método estático y se sale con la suya porque sayHi() nunca se refiere a $this.

Las funciones estáticas están asociadas con la clase, no con una instancia de la clase. Como tal, $this no está disponible desde un contexto estático ($this no apunta a ningún objeto).

 143
Author: Jonathan Fingland,
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-12-20 03:01:20

Simplemente, las funciones estáticas funcionan independientemente de la clase a la que pertenecen.

Means esto significa, esto es un objeto de esta clase. No se aplica a funciones estáticas.

class test {
    public function sayHi($hi = "Hi") {
        $this->hi = $hi;
        return $this->hi;
    }
}
class test1 {
    public static function sayHi($hi) {
        $hi = "Hi";
        return $hi;
    }
}

//  Test
$mytest = new test();
print $mytest->sayHi('hello');  // returns 'hello'
print test1::sayHi('hello');    //  returns 'hello'
 20
Author: user2132859,
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
2013-08-27 15:36:06

Toda la diferencia es que no obtienes $this suministrado dentro de la función estática. Si intentas usar $this, obtendrás un Fatal error: Using $this when not in object context.

Bueno, vale, otra diferencia: una advertencia E_STRICT es generada por tu primer ejemplo.

 19
Author: chaos,
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-05-24 02:15:02

Llamar a métodos no estáticos genera estáticamente una advertencia de nivel E_STRICT.

 3
Author: ,
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-09-02 18:40:32

En pocas palabras, no tienes el objeto como this esto en el segundo caso, como el método estático es una función/método de la clase no la instancia del objeto.

 2
Author: Czimi,
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-05-24 02:17:28

Después de probar ejemplos (PHP 5.3.5), encontré que en ambos casos de definir funciones no se puede usar el operador $this para trabajar en funciones de clase. Así que no pude encontrar una diferencia en ellos todavía. :(

 1
Author: yogesh,
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-30 08:08:08