Avatar of rgb192
rgb192
Flag for United States of America asked on

I do not understand why properties are declared.

<?php
class Student{
 private $name;
 public $age;
 public function __construct($name,$age){
   $this->name=$name;
   $this->age=$age;
   $this->sum=$name+$age;
 }
}
$tmpStudent=new Student("Mindi","22");
echo "Age : ". $tmpStudent->age;
echo "<br>Sum:".$tmpStudent->sum;

Open in new window



I am typing from a code tutorial.

I think a good way of learning is by adding lines to the existing code.

So I added $this->sum which still displayed but did not need to be declared as a property above the constructor.

Why are properties declared?
PHP

Avatar of undefined
Last Comment
Ray Paseur

8/22/2022 - Mon
SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Loganathan Natarajan

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
rgb192

ASKER
Okay
for organization
and security (I do not understand yet)

Thank you.
Ray Paseur

Sorry, I forgot to add one other reason to declare your properties... You control the order of their appearance in the output from var_dump() and print_r().  This can matter if you have a large number of properties!
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23