2011-06-13 106 views
-2

可能重复:
To pass value of a variable in one function to another function in same class使用全局变量

在一个函数变量的值在其他功能提供在PHP中使用“全球”同一类。如果是这样,请建议如何使用Global进行实现。

+2

你有没有再问同样的问题? http://stackoverflow.com/questions/6289352/to-pass-value-of-a-variable-in-one-function-to-another-function-in-same-class – afarazit 2011-06-13 01:03:15

+0

全球?在同一班级的另一个功能?私人类变量有什么问题? – hakre 2011-06-13 01:03:33

+0

实际上,第一个函数中使用的变量的值是传递给第一个函数的参数。我想这是可用的第二个功能,是否有可能通过使用GLOBAL – dhaam 2011-06-13 01:06:25

回答

5

如果您位于对象内,则不需要创建变量GLOBAL。

class myClass { 

    public $myVar = "Hello"; 

    function myFunction() { 
    echo $this->$myVar; 
    } 

} 

这是对象的要点之一 - 您可以为变量赋值不同的值,并在不同的方法中获取/设置这些变量。此外,您可以创建多个对象实例,每个对象都拥有相同结构内的不同信息并使用相同的方法。

+0

+1对于实际回答问题。虽然实际上这个解决方案的行为不像_global_,因为非静态属性会在类的不同实例间发生变化。 – Tadeck 2011-06-13 01:27:20

0

是的,一个函数中的变量值可以在同一个类的另一个函数中使用“GLOBAL”提供。下面的代码打印3

class Foo 
{ 
    public function f1($arg) { 
    GLOBAL $x; 
    $x = $arg; 
    } 
    public function f2() { 
    GLOBAL $x; 
    return $x; 
    } 
} 

$foo = new Foo; 
$foo->f1(3); 
echo $foo->f2(); 

然而,全局变量的使用通常是设计不良的标志。

请注意,虽然PHP中的关键字不区分大小写,但它们是自定义的小写字母。不仅如此,包含所有全局变量的超全局数组称为$GLOBALS,而不是GLOBAL

+0

让我试试吧奥斯瓦尔德,谢谢 – dhaam 2011-06-13 01:14:59

+0

使用全球也无法实现 – dhaam 2011-06-13 01:31:31

2

此外什么@Codecraft说(关于使用公共属性),你可以使用:

  • 确实全局变量(这是真正的东西,你应该避免这样做),在参数
  • 传递值,
  • 类中
  • 静态变量,

下面是一个使用静态变量(私营),因为我觉得THI的例子西服您的需求最好的:

class MyClass { 
    private static $_something; 
    public function write() { 
     static::$_something = 'ok'; 
    } 
    public function read() { 
     return static::$_something; 
    } 
} 

$x = new MyClass(); 
$x->write(); 
var_dump($x->read()); 

,输出:

字符串(2) “OK”

这其实是像一个全球性的,但只能从(因为关键字“私人”)和常见的实例t他班。如果你使用设置一些非静态属性,它会改变类的不同实例(一个对象可能有不同的值存储在它比其他对象有)。基于静态和非静态变量的解决方案的

比较:基于

解决方案静态变量会给你真的全球类似的行为(在不同的情况下,通过同一个类的值) :

class MyClass { 
    private static $_something; 
    public function write() { 
     static::$_something = 'ok'; 
    } 
    public function read() { 
     return static::$_something; 
    } 
} 

// first instance 
$x = new MyClass(); 
$x->write(); 
// second instance 
$y = new MyClass(); 
var_dump($y->read()); 

,其输出:

字符串(2) “OK”

而基于非静态变量的解决方案看起来像:

class MyClass { 
    private $_something; 
    public function write() { 
     $this->_something = 'ok'; 
    } 
    public function read() { 
     return $this->_something; 
    } 
} 

// first instance 
$x = new MyClass(); 
$x->write(); 
// second instance 
$y = new MyClass(); 
var_dump($y->read()); 

而是将输出:

NULL

这意味着在这种情况下,第二个实例没有为变量分配值,您想表现得像“全局”。