2011-04-25 3 views
1

Je ne comprends pas pourquoi ça ne marche pas de code:appeler un tableau privé d'un autre tableau privé en php

<?php 
class Test { 

    private $BIG = array(
     'a' => 'A', 
     'b' => 'B', 
     'c' => 'C' 
    ); 

    private $arr2 = array(
     $this->BIG['a'], 
     $this->BIG['b'], 
     'something' 
    ); 

    public function getArr2(){ 
     return $this->arr2; 
    } 


} 

$t = new Test(); 
print_r($t->getArr2()); 

?> 

Je reçois cette erreur:

Parse error: syntax error, unexpected T_VARIABLE, expecting ')' in /home/web/te/test.php on line 11

Répondre

2

Vous ne pouvez pas combiner des variables dans une définition de membre de la classe. Vous ne pouvez utiliser des types et des constantes natives:

private $arr = array('a', 'b'); 
private $obj = new stdClass(); // error 
private $obj = (object)array(); // error 
private $num = 4; 
private $a = 1; 
private $b = 2; 
private $c = $this->a + .... // error 

Si vous voulez combiner ou calculer, faire en __construct:

private $a = 1; 
private $b = 2; 
private $c; 

function __construct() { 
    $this->c = $this->a + $this->b; 
} 
1

Vous ne pouvez pas référencer $ this lors de la déclaration des propriétés.

1

De l'PHP Documentation:

[Property] declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

Par conséquent, faire des actions comme ça dans le constructeur:

class Test { 

    private $BIG = array(
     'a' => 'A', 
     'b' => 'B', 
     'c' => 'C' 
    ); 

    private $arr2; 

    public function __construct() 
    { 
     $this->arr2 = array(
      $this->BIG['a'], 
      $this->BIG['b'], 
      'something' 
     ); 
    } 

    public function getArr2(){ 
     return $this->arr2; 
    } 
}