2014-03-03 136 views
1

我有这样的代码:设置属性的静态类

<?php 

class test { 
    public static function plus($input) { 
     $conf = variable_get('config'); 
     $b = $conf['var']; 
     return (int)$input + (int)$b; 
    } 

    public static function minus($input) { 
     $conf = variable_get('config'); 
     $b = $conf['var']; 
     return (int)$input - (int)$b; 
    } 
} 

,而不是调用variable_get在每个方法加载配置,我想设置的属性配置,这样我就可以把它所有的方法里面。 如何创建它?我试图创建public function __construct() {}并设置属性,但仍然无法在方法中调用它。

感谢,

+0

什么是'variable_get'?这是在[标签:Drupal]? – Phil

回答

1

试试这个

<?php 
    function variable_get($p) { 
    $arr = array('config' => array('var' => 4)); 
    return $arr[$p]; 
    } 
    class test { 
     public static $config_var = array(); 
     public static function plus($input) { 
     $conf = self::$config_var; 
     $b = $conf['var']; 
     return (int)$input + (int)$b; 
    } 

    public static function minus($input) { 
     $conf = self::$config_var; 
     $b = $conf['var']; 
     return (int)$input - (int)$b; 
    } 
} 

test::$config_var = variable_get('config'); 
echo test::plus(12); 
echo test::minus(12); 


?> 
+0

谢谢,解决了它:) – kelaskakap

1

负载,并得到配置或设置文件,您可以使用parse_ini_file:

parse_ini_file - 解析一个配置文件

实例#1目录的sample.ini

; This is a sample configuration file 
; Comments start with ';', as in php.ini 

[first_section] 
one = 1 
five = 5 
animal = BIRD 

[second_section] 
path = "/usr/local/bin" 
URL = "http://www.example.com/~username" 

[third_section] 
phpversion[] = "5.0" 
phpversion[] = "5.1" 
phpversion[] = "5.2" 
phpversion[] = "5.3" 

的index.php内容

<?php 

define('BIRD', 'Dodo bird'); 

// Parse without sections 
$ini_array = parse_ini_file("sample.ini"); 
print_r($ini_array); 

// Parse with sections 
$ini_array = parse_ini_file("sample.ini", true); 
print_r($ini_array); 

?> 

以上例程的输出类似的东西,以:

Array 
(
    [one] => 1 
    [five] => 5 
    [animal] => Dodo bird 
    [path] => /usr/local/bin 
    [URL] => http://www.example.com/~username 
    [phpversion] => Array 
     (
      [0] => 5.0 
      [1] => 5.1 
      [2] => 5.2 
      [3] => 5.3 
     ) 

) 
Array 
(
    [first_section] => Array 
     (
      [one] => 1 
      [five] => 5 
      [animal] => Dodo bird 
     ) 

    [second_section] => Array 
     (
      [path] => /usr/local/bin 
      [URL] => http://www.example.com/~username 
     ) 

    [third_section] => Array 
     (
      [phpversion] => Array 
       (
        [0] => 5.0 
        [1] => 5.1 
        [2] => 5.2 
        [3] => 5.3 
       ) 

     ) 

) 

简单的类定义

<?php 
class SimpleClass 
{ 
    // property declaration and access from all method 
    public $var = 'a default value'; 
    public $ini_array = parse_ini_file("sample.ini"); 


    // method declaration 
    public function displayVar() { 
     echo $this->var; 
     print_r($this->$ini_array); 
    } 
} 

$Simpleclass = new SimpleClass(); 
$Simpleclass->displayVar(); 
?>