-1
class Automobile
{
    public $fuel;
    protected $engine="1500CC";

    public function eng(){
        return($this->engine);
    }
}

$automobile = new Automobile;
echo $automobile->fuel = 'Petrol'; 
echo $automobile->engine; 
echo $automobile->eng(); 

Here echo $automobile->engine; cause me fatal error. That is correct. NoI i created a public function eng() to use the protected variable engine outside the class it works for me.

My question is by using the public function I can access the protected variable so then I can access it anywhere so basically I converted protected variable to public variable this is a statement in bold is right??

Tom Regner
  • 6,856
  • 4
  • 32
  • 47
  • You cannot change the value of it. you are indirectly accessing the value of that var. – Thamaraiselvam Apr 13 '18 at 07:35
  • 1
    No. You still cannot assign to the variable unless you also write a setter function, so there's a difference. – deceze Apr 13 '18 at 07:35
  • 2
    You did not convert variable. You just provide a method to get protected variable's value outside of a class. Variable remains protected. – u_mulder Apr 13 '18 at 07:37
  • You are not converting any var , you are just accessing. as @deceze mentioned, there is a difference . – Thamaraiselvam Apr 13 '18 at 07:37
  • 1
    You haven't converted that variable, you have just created a method which return a copy of value of the protected variable. – jagad89 Apr 13 '18 at 07:41

3 Answers3

2

Technically not. Your attribute is still protected, but you can get its value through a getter method.

Here you created a getter method, which allows you to get the value of an attribute of your class.

Using getters and setters is a good practice as described here and here.

Hope it helps.

xyzale
  • 745
  • 8
  • 14
0

No. You can read its value, but not change it. You wont be able to change the engine string by using something like $automobile->eng() = "2000CC", because the function returns the value, not the variable.

Gudra
  • 70
  • 10
0

There is no harm in exposing scalar/simple values of protected variables through public methods. The whole point of this is to have a greater control over how the internal state of your object is managed and presented to the "outside world".

This is particularly useful when you want to make sure that protected variable is of certain type.

Jinksy
  • 421
  • 4
  • 11