[PHP] OOP | Zugriff auf statisches Attribut einer Klasse mit variablem Klassennamen

Dieses Thema im Forum "Webentwicklung" wurde erstellt von myth2806, 25. Juli 2010 .

Status des Themas:
Es sind keine weiteren Antworten möglich.
  1. 25. Juli 2010
    OOP | Zugriff auf statisches Attribut einer Klasse mit variablem Klassennamen

    Hey,

    hab eine ganz kurze Frage.
    Wie muss ich das ganze formulieren um auf ein statisches Attribut eines variablen Klassennamens zuzugreifen? Das ganze ist aber noch in einer anderen Klasse verschachtelt. Hier ein Beispielcode.

    PHP:

    <?php

    class  foo
    {
       public static 
    $x  '123abc' ;
    }

    class 
    bar
    {
        protected 
    $ClassName ;
        
        public function 
    __construct $ClassName  )
        {
            
    $this -> ClassName  $ClassName ;
        }
        
        public function 
    func ()
        {
            print 
    $this -> ClassName :: $x // <-- Zeile 19
        
    }
    }



    $Obj  = new  bar 'foo'  );
    $Obj -> func ();

    // Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in test.php on line 19


    ?>

    Wie Stell ich das an?

    Grüße
     
  2. 25. Juli 2010
    AW: OOP | Zugriff auf statisches Attribut einer Klasse mit variablem Klassennamen

    du musst den klassen-namen zuerst auf eine variable reduzieren, dann gehts.

    PHP:
    <? php

    public function  func ()
    {
        
    $class  $this -> ClassName ;
        print 
    $class :: $x ;
    für php < 5.3 musst dir nen workaround basteln z.b.:

    PHP:
    <? php

    class  foo
    {
        public static 
    $x  '123abc' ;

        public static function 
    getStaticMember ( $name )
        {
            return 
    self ::$ $name ;
        }
    }

    class 
    bar
    {
        protected 
    $ClassName ;
        
        public function 
    __construct $ClassName  )
        {
            
    $this -> ClassName  $ClassName ;
        }
        
        public function 
    func ()
        {
            
    $val  call_user_func (array( $this -> ClassName 'getStaticMember' ),  'x' );
            print 
    $val ;
        }
    }



    $Obj  = new  bar 'foo'  );
    $Obj -> func ();



    ?> 
     
  3. 25. Juli 2010
    AW: OOP | Zugriff auf statisches Attribut einer Klasse mit variablem Klassennamen

    OK super das funktioniert. Danke dir!

    Hatte bisher ebenfalls das Workaround mit call_user_func() nur ich dachte mir das muss doch auch eleganter gehen.
    Schade dass sich kein Einzeiler draus machen lässt

    Grüße
     
  4. 25. Juli 2010
    AW: OOP | Zugriff auf statisches Attribut einer Klasse mit variablem Klassennamen

    upgrade auf php 5.3

    [X] erledigt

    closed
     
  5. Video Script

    Videos zum Themenbereich

    * gefundene Videos auf YouTube, anhand der Überschrift.