2

when making a class in php what is the difference between these two :

class Search 

    function __construct()
    {

        $this->variable1= 1234;      

    }
}

and

class Search 

    private $variable1;

$variable1=1234;

    function __construct()
    {

    }
}

if i need to access a value across different methods does it make any difference which approach i chose?

thank you

1
  • 1
    One difference is that second version doesn't parse. Commented Mar 23, 2011 at 14:55

4 Answers 4

6

The difference between object and class variables is how you can access them.

  • object variable: $obj->var
  • class variable: class::$var

Your class definition should be:

class Search {
    static $variable = 2;   // only accessible as Search::$variable
}

Versus:

class Search2 {
    var $variable = "object_prop";
}

Wether you use var or public or the private access modifier is not what makes a variable an object property. The deciding factor is that it's not declared static, because that would make it accessible as class variable only.

Sign up to request clarification or add additional context in comments.

Comments

2

The are essentially the same thing however if you do not declare the variable/property before it is called you will get a warning saying the variable doesn't exist.

It is best practice to do it this way:

class Search {

  private $_variable1;

  function __construct() {
    $this->_variable1=1234;
  }

}

Note: private variables are only available to the class they are declared in.

2 Comments

no they aren't, $this->variable will declare the variable as public, ok you edited it... this is a merge of his two approaches ^^
@sharpner. Ya I caught that after I answered. However the question is accessing variable within different methods, not from outside the class.
2

Well for star ( just for better practices ) use _ ( underscores ) if a method or property is private/protected , so you're code should look like this :

class Search 
{
    private $_variable1 = 1234;

    //example usage
    public function someMethod()
    {
        if ( $this->_variable1 == 1234 ) {
           //do smth
        }
    }
}

Comments

1

in your first approach the variable is not declared private, so you can access the variable from outside the object, whereas in your second approach only allows the usage inside of the class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.