[Solved] When to use $this and when simple variable


In OOP:
$this->name is property of the object which is defined by the class and is accessible globally within the object.
$name is variable used inside the class method and is accessible locally only within the object method (a function)

Very briefly:

class myClass{

    private $name = "record.log";

    function myMethod(){
      $name="this exists only in the method myMethod()";
      $this->name; // this contains the 'record.log' string
    }

}

From outside the class you cannot access the variable $name defined within an object.

You can only access the property $name defined in the class but from outside of the object you must call it using the object name:

$obj = new myClass();
$log_file = $obj->name; // this would contain the string 'record.log'

However you defined the object property as private so the direct access will be restricted from outside of the object. To be able to access it you have to define getter/setter a methods that will handle read/write to private property.

// add to the class methods
public function getName(){
  return $this->name;
}

public function setName($value){
  // do some validation of the value first
  //...
  // then assign the value 
  $this->name = $value; 
}

So now you can access the object property $name from outside of the object using statements:

echo $obj->getName();  // prints record.log
$obj->setName('new.log');
echo $obj->getName();  // prints new.log

3

solved When to use $this and when simple variable