2016-03-30 1 views
2

j'ai deux classes (modèle et utilisateur) mais j'ai un problème donc j'ai essayé de l'expliquer dans un exemple simple:passer outre une variable statique

class person 
{ 
    protected static $todo ="nothing"; 

    public function __construct(){} 

    public function get_what_todo() 
    { 
     echo self::$todo; 
    } 
} 

class student extends person 
{ 
    protected static $todo ="studing"; 
} 

$s = new student(); 
$s->get_what_todo(); // this will show the word (nothing) 
        //but I want to show the word (studing) 

S'il vous plaît me donner une solution, mais sans écrire de fonction dans la catégorie des étudiants, je veux seulement faire des déclarations là :) et je vous remercie :)

+3

[liaison statique tardive] (http://php.net/manual/en/language.oop5.late-static-bindings.php) ..... la différence entre 'echo self :: $ todo;' et 'echo static :: $ todo;' –

+0

merci beaucoup, vous venez de me sauver la vie, Ajoutez votre commentaire comme une réponse si vous veux :) :) –

+0

Heh, Nice Mark;) – Farkie

Répondre

3

le principe est appelé "late static binding ", et a été introduit en PHP 5.3.0; avec le mot clé self pour accéder à la propriété définie dans la classe appelante dans l'arborescence d'héritage, ou static pour accéder à la propriété définie dans la classe enfant dans cette arborescence d'héritage.

class person 
{ 
    protected static $todo ="nothing"; 

    public function __construct(){} 

    public function get_what_todo() 
    { 
     echo static::$todo; // change self:: to static:: 
    } 
} 

class student extends person 
{ 
    protected static $todo ="studying"; 
} 

class teacher extends person 
{ 
    protected static $todo ="marking"; 
} 

class guest extends person 
{ 
} 

$s = new student(); 
$s->get_what_todo(); // this will show the "studying" from the instantiated child class 

$t = new teacher(); 
$t->get_what_todo(); // this will show the "marking" from the instantiated child class 

$g = new guest(); 
$g->get_what_todo(); // this will show the "nothing" from the parent class, 
        // because there is no override in the child class 
1

vous pouvez essayer dans la construction variable établie

class person 
{ 
    protected static $todo = null; 

    public function __construct(){ 
     self::$todo = "nothing"; 
    } 

    public function get_what_todo() 
    { 
     echo self::$todo; 
    } 
} 

class student extends person 
{ 
    public function __construct() { 
     self::$todo = "student"; 
    } 
} 

$s = new student(); 
$s->get_what_todo(); 
0

vous pouvez essayer de variable parent de la construction

class person 
{ 
    protected static $todo = null; 

    public function __construct(){ 
     self::$todo = "nothing"; 
    } 

    public function get_what_todo() 
    { 
     echo self::$todo; 
    } 
} 

class student extends person 
{ 
    public function __construct() { 
     parent::$todo = "student"; 
    } 
} 

$s = new student(); 
$s->get_what_todo();