@benitto_raj No, it's not necessary, they would default to public. It's a good habit to get into the practice of doing though. It's much easier to look at the top of a class and see all its explicitly defined properties rather than searching thru all the methods.
Usually, you want to avoid using public properties whenever possible. Having public properties means they can be mutated from anywhere in your app (outside the class) and that is generally considered a bad thing.
No it's not necessary. If you do it in the constructor you need to pass all the values when you instanciate the class and that can becode very cumbersome.
Take this user class for example
class User
{
protected $firstName;
protected $lastName;
protected $email;
protected $workPhone;
protected $homePhone;
protected $cellPhone;
public function _contruct($firstName, $lastName)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function setEmail($email)
{
$this->email = $email;
}
//And so on.
}
The first and last name are the only mandatory fields thus are passed into the constructor. You can if you want pass all of them in but it's better to keep the parameters to a minimum. Then set the other properties if need be with setters. Since it's most likely that email addresses and phone numbers change and less likely that a person change their name (not unheard of but just less likely).
Thank you for your previous replies.
i had declared $subjects as public when the store method get invoked it have the database details .but when calculate method invoked $subjects losts it's value.but if i echo $name in calculate method it will echo "benitto" correctly?why $subjects only losts it values? what is the reason how to i fix it?
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class GpaController extends Controller
{
public $name = "benitto";
public $subjects;
public function store(Request $request)
{
$dep = $request->get('dept');
$sem = $request->get('sem');
$dept_code = DB::table('departments')->where('department',$dep)->first();
$this->subjects = DB::table('2017s')->where([['dept_code',$dept_code->code],['sem',$sem]])->get();
return view('Gpa.subjects')->with('subjects', $this->subjects);
}
public function calculate(Request $request)
{
$grades = $request->all();
$sum =$total=0;
foreach ($this->subjects as $subject)
{
echo $grades[$subject->subject_code]." * ".$subject->credit."<br>" ;
$temp = $grades[$subject->subject_code];
$sum = $sum + ($temp*$subject->credit);
$total = $total + $subject->credit;
}
return "<br>".$sum/$total;
}
}