2014-03-01 250 views
0

稍后我会解释这一点:全局变量

class num 
{ 
    function num1() 
    { 
     global $error; 
     $error="This is an error message"; 
     return false; 
    } 

    function num2() 
    { 
     global $error; 
     return $error; 
    } 
} 

$num=new num(); 
$check=$num->num1(); 
if($check===false) $error.="There is another error message"; 

die($error);//This is an error messageThere is another error message 

在功能num1$error影响$error类外。有关如何防止这种情况的任何建议?

+0

您错过了分号,在返回虚假陈述结束 – Sandesh

+0

谢谢,但这不是我想要得到的答案:D但是,谢谢。 – 131

+0

我想它是因为你使用全局。停止它,它不会影响对象外部的$错误。 –

回答

1

你应该使用对象的字段(属性):

class num 
{ 
    protected $error; 

    public function num1() 
    { 
     $this->error = "This is an error message"; 
     return false; 
    } 

    public function num2() 
    { 
     return $this->error; 
    } 
} 

$num = new num(); 
$check = $num->num1(); 
if ($check===false) { 
    // $error is just local variable, not defined before 
    $error .= "There is another error message"; 

    // $objError is the error message from object 
    $objError = $num->num2(); 
} 

全局变量是反模式。面向对象的一个​​原理是封装。你不想公开$ error变量,除非有一个方法(契约)返回它。这正是你可以用私人或受保护的资产做的事情。

我推荐你读一些这样的:http://www.php.net/manual/en/language.oop5.php

另外,还要考虑尤为明显类,方法和变量名。 num1num2是你可能选择的最差的一个。但我明白这是一个例子。

+0

谢谢,这工作!我终于可以摆脱所有功能中的'global $ error':-D – 131

+1

如果这对你来说是新的(它有帮助),你应该*阅读一些OOP的基础知识(我发布的链接)。这将为你打开一个新的世界。不用谢。 –

+0

我会的,谢谢。 PHP对我来说就像宇宙,它是无限的! – 131