从全局函数设置类变量

时间:2014-03-26 06:47:25

标签: php methods

尝试做这样的事情:

Class Example {
    public static $current_item;
}

function example_global($var1) {
    if ($var1)
        Example::$current_item = $var1;
}

这可能吗?

3 个答案:

答案 0 :(得分:1)

是的,这应该有点问题:小心这个:

if ($var1)

因为您无法设置值0

答案 1 :(得分:1)

代码有效:

Class Example {
    public static $current_item;
}

function example_global($var1) {
    if ($var1)
        Example::$current_item = $var1;

}

example_global('hello there!<br>');
echo Example::$current_item;
example_global('hello there again!');
echo Example::$current_item;

结果:

hello there!
hello there again!

因此,请确保首先在您使用它的文件中包含该类。

答案 2 :(得分:0)

Example类中的static变量$current_item将使用从函数传递的任意值进行设置。

如果您通过example_global($50);,则会设置$current_item值。

<?php

Class Example {
    public static $current_item;
}

function example_global($var1) {
    if ($var1)
        Example::$current_item = $var1;
}

example_global(20);
var_dump(Example::$current_item); 

<强> OUTPUT :

(int) 20

即便如果你删除了public修饰符,那也是可行的。

来自PHP文档..

  

如果没有使用可见性声明,那么属性或方法将会   被视为公开宣称。

相关问题