<?php
class Product {
private $id;
private $name;
private $price;
private $lastUpdate;
private $category;
//public function Product($id) {
// $this->id = $id;
//}
public function Product($id, $name, $price, $lastUpdate) {
$this->id = $id;
$this->name = $name;
$this->price = $price;
$this->lastUpdate = $lastUpdate;
}
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getPrice() {
return $this->price;
}
public function setPrice($price) {
$this->price = $price;
}
public function getLastUpdate() {
return $this->lastUpdate;
}
public function setLastUpdate($lastUpdate) {
$this->lastUpdate = $lastUpdate;
}
public function getCategory() {
return $this->category;
}
public function setCategory($category) {
$this->category = $category;
}
}
?>
Thanks! I see. @Lemon Juice: Do you see a paragraph I marked by orange color in Product class? As Java or C#, I can make a lot of construct function with one, two, …etc parameter(s) but in PHP, I can’t. When I try to do this, I see an error:
Fatal error: Cannot redeclare Product::Product() in C:\xampp\htdocs\demo\passing_object_to_function\product.php on line 13
I see, you mean method overloading. It’s not possible in PHP, the closest you can get to it is accept optional parameters and then use if statements to do different things:
public function Product($id, $name = null, $price = null, $lastUpdate = null) {
if ($name === null && $price === null && $lastUpdate === null) {
// do something when only $id is given...
} else {
// do something else...
}
}
actually you can use func_get_args() and manually code the branching, but it’s a bit hacky and makes it very difficult for people using the class to see what is needed by the constructor:
class Test {
public function __construct() {
print_r(func_get_args());
}
}
new Test(1, 2);
new Test('A', 'B', 'C');