131
131

Reputation: 1385

Global variables in class and outside class

I'll explain this shortly:

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

$error in the function num1 affect $error outside the class. Any suggestions on how i can prevent this?

Upvotes: 0

Views: 41

Answers (1)

Pavel S.
Pavel S.

Reputation: 12352

You should use object fields (properties):

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();
}

Global variables are antipattern. One of the priciples of OO is encapsulation. You don't want to expose the $error variable, unless there is a method (contract) returning it. Which is exactly what you can do with private or protected properties.

I recommend you reading some of this: http://www.php.net/manual/en/language.oop5.php

Also, consider beter class, method and variable names. num1 and num2 are one of the worst you might have chosen. But I understand this is an example.

Upvotes: 1

Related Questions