2011-08-14 12 views
12

में फ़ाइल शामिल है क्या कक्षा के अंदर php चर के साथ फ़ाइल शामिल करना संभव है? और सबसे अच्छा तरीका कैसे होगा ताकि मैं पूरी कक्षा के अंदर डेटा तक पहुंच सकूं?php में कक्षा

मैं थोड़ी देर के लिए यह गुगल रहा हूं, लेकिन उदाहरणों में से कोई भी काम नहीं करता है।

धन्यवाद, Jerodev

+1

तुम क्या आप क्या करना चाहते पर कुछ अधिक विस्तार कर सकते हैं? –

+2

और कृपया इंगित करें कि http://stackoverflow.com/search?q=include+file+in+class+php में से कोई भी आपके प्रश्न का उत्तर नहीं देता है। – Gordon

+0

ऐसा करना बहुत असंभव प्रतीत होता है, इसलिए मैं बाहरी डेटा लोड करने के लिए एक्सएमएल का उपयोग करूँगा। – Jerodev

उत्तर

13

सबसे अच्छा तरीका उन्हें लोड करने के लिए है, उन्हें बाहरी फ़ाइल के माध्यम से शामिल करने के लिए नहीं

जैसे:

// 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

असल में, आप डेटा चर करने के लिए संलग्न करना होगा ।

<?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

देखने का प्रदर्शन बिंदु से, यह बेहतर होगा यदि आप .ini फ़ाइल का उपयोग आपकी सेटिंग रखने की होगी।

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

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

और फिर अपनी कक्षा में आप कुछ इस तरह कर सकते हैं:

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 
    } 
} 
संबंधित मुद्दे