oop - Is PHP class variable definition necessary? -


I am new to PHP object-oriented programming but I know the code in a procedural way.

If this is my PHP class

   

And if I use it in my PHP page

  $ jane = new person ("Jane Do"); The echo "His name is:". $ Jane- & gt; Get_name ();  

Question: In my PHP class, var $ name; It is really necessary to put , because I can get the output of name: jane do even var $ name Without in my PHP class? As a terminology, you should know that your class is actually $ name

$ persons_name , but if you have var $ name; , the rest of your script really does not know that such a feature is in your class. In addition, if your constructor has not specified this immediately, then person :: get_name () will try to recover an undeclared $ name attribute and trigger a notice .

As you explicitly declare your class attributes, you can set their visibility, for example, when your get_name () becomes $ name < / Code> in the form of gates, you can set $ name as private so that you person object After making a person's name can not be changed outside the class.

In addition to trying to assign undeclared square properties, they can be declared as public before they are specified.


Comments