在静态类中设置属性

时间:2014-03-03 04:53:50

标签: php static-classes

我有这段代码:

<?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() {}并设置属性,但仍无法在方法内调用它。

感谢,

2 个答案:

答案 0 :(得分: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();
?>

答案 1 :(得分: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);


?>