You're requiring the $pc
parameter for your function call, so you'll get an error before you ever reach the isset()
check. Try public function rotate($a, PointCartesien $pc = null) {
, then use the is_null
check in place of isset
.
How to use default value if unset parameter is an object
سؤال
I need to build a method where an object is passed as parameter. This method is using PHP "instanceof" shortcut.
//Class is setting a coordinate.
class PointCartesien {
//PC props
private $x;
private $y;
//Constructor
public function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
//The method in question... It makes the coordinate rotate using (0,0) as default and $pc if set.
//Rotation
public function rotate($a, PointCartesien $pc) {
//Without $pc, throws error if empty.
if(!isset($pc)) {
$a_rad = deg2rad($a);
//Keep new variables
$x = $this->x * cos($a_rad) - $this->y * sin($a_rad);
$y = $this->x * sin($a_rad) - $this->y * cos($a_rad);
//Switch the instance's variable
$this->x = $x;
$this->y = $y;
return true;
} else {
//...
}
}
}
Using isset() throws an error. The way I want it to work is by setting $pc parameters rotate($a, PointCartesien $pc = SOMETHING) to (0,0) as default. How would I do that?
المحلول
لا تنتمي إلى StackOverflow