0

I am trying to learn php class. I am getting confused about which properties should have to declare inside class. I am giving a simple example to understand the situation:

class main{
var $a=5;
var $b;
 function add($c){
 return $this->a + $this->b + $c;
 }
}

$load = new main();
$load-> $b=10;
echo $load->add(20); //will output 35

In the above case, please see that I did not declare property $c inside class. It is directly accessing from the call $load->add(20) and it is working well. My question is although this is working, but is it right way or I have to declare the $c property in this case? NB: May be this is working due to set magic method of oop, not sure.

stockBoi
  • 287
  • 2
  • 9
  • 26

1 Answers1

0

There are some errors, the parenthesis after the classname (main) and the $ before the var $b, the $ before b in the penultimate line.

Anyway, no magic here, you declared a class with $a and $b variables (class attributes): then you wrote the method add, which takes a local parameter ($c), and adds it to the attributes $a and $b of the current object.

After the method execution, you'll lose the value passed to the method, assigned to $c.

Your example is correct and you don't have to declare $c if you just want to use it this way; on the contrary, you'd need to declare it among the other class attributes if you want to use it as an object attribute, for example to use it in another method. In this case, you'll have to declare it first in the class, then use it as $this->c:

e.g.:

class main {
   ...
   var $c;

   function test($c){
     $this->c = $c;
     ...
   }
}

Note that $this->c and $c are two different variables: $c is just in the scope of the method, as said before.

Lorenzo Marcon
  • 8,029
  • 5
  • 38
  • 63