I am learning alone PHP from websites. I have some OOP background on other languages.
Question 1:
Is this the correct way to implement a constructor in PHP with 2 different set of parameters ?
Question 2:
When I'm coming to __set magic method in PHP I want that the comment_id in this class cannot be changed from __set function. Can this be possibly done in PHP?
class Comment{
private $comment_id;
private $image_id;
private $author_id;
private $comment_text;
private $created_at;
public function __construct()
{
$arguments = func_get_args();
$num = sizeof($arguments)
switch($num)
{
case 0;
break;
case 3:
this->image_id = $arguments[0];
this->author_id = $arguments[1];
this->comment_text = $argument[2];
break;
case 5:
this->comment_id = $arguments[0];
this->image_id = $arguments[1];
this->author_id = $argument[2];
this->comment_text = $argument[3];
this->created_at = $argument[4];
break;
default:
break;
}
}
public function __get($property)
{
if(property_exists($this,$property))
{
return $this->$property;
}
}
public function __set($property_name,$value)
{
if(property_exists($this,$property_name))
{
$this->$property_name = $value;
}
}
}
There are many ways of declaring 'multiple' constructors in PHP, but none of them are the 'correct' way of doing so (since PHP technically doesn't allow it). I don't see anything wrong with how you're doing it there, however. If you'd like more information, check out this Stack Overflow question.
You could just use an if
statement. Something like this, perhaps?
public function __set($property_name,$value)
{
$hidden_properties = array(
'comment_id',
'any_other_properties'
);
if(!in_array($property_name, $hidden_properties) &&
property_exists($this, $property_name))
{
$this->$property_name = $value;
}
}