2011-08-14 23 views
12

¿Es posible incluir un archivo con variables php dentro de una clase? ¿Y cómo sería la mejor manera para que pueda acceder a los datos dentro de toda la clase?php include file en la clase

He estado buscando en Google por un tiempo, pero ninguno de los ejemplos funcionó.

Gracias, Jerodev

+1

¿Se puede ampliar un poco más de lo que quiere hacer? –

+2

y señale por qué ninguno de http://stackoverflow.com/search?q=include+file+in+class+php respondió su pregunta. – Gordon

+0

Parece bastante imposible hacer esto, entonces usaré xml para cargar datos externos. – Jerodev

Respuesta

13

la mejor manera es para cargarlos, no incluirlos a través archivo externo

por ejemplo:

// config.php 
$variableSet = array(); 
$variableSet['setting'] = 'value'; 
$variableSet['setting2'] = 'value2'; 

// load config.php ... 
include('config.php'); 
$myClass = new PHPClass($variableSet); 

// in class you can make a constructor 
function __construct($variables){ // <- as this is autoloading see http://php.net/__construct 
    $this->vars = $variables; 
} 
// and you can access them in the class via $this->vars array 
1

En realidad, se debe añadir datos a la variable .

<?php 
/* 
file.php 

$hello = array(
    'world' 
) 
*/ 
class SomeClass { 
    var bla = array(); 
    function getData() { 
     include('file.php'); 
     $this->bla = $hello; 
    } 

    function bye() { 
     echo $this->bla[0]; // will print 'world' 
    } 
} 

?>

1

Desde el punto de vista del rendimiento, que sería mejor si va a utilizar el archivo .ini para almacenar la configuración.

[db] 
dns  = 'mysql:host=localhost.....' 
user  = 'username' 
password = 'password' 

[my-other-settings] 
key1 = value1 
key2 = 'some other value' 

Y luego en su clase que puede hacer algo como esto:

class myClass { 
    private static $_settings = false; 

    // this function will return a setting's value if setting exists, otherwise default value 
    // also this function will load your config file only once, when you try to get first value 
    public static function get($section, $key, $default = null) { 
     if (self::$_settings === false) { 
      self::$_settings = parse_ini_file('myconfig.ini', true); 
     } 
     foreach (self::$_settings[$group] as $_key => $_value) { 
      if ($_key == $Key) return $_value; 
     } 
     return $default; 
    } 

    public function foo() { 
     $dns = self::get('db', 'dns'); // returns dns setting from db section of your config file 
    } 
}