【发布时间】:2025-11-23 22:40:01
【问题描述】:
我需要构建一个将对象作为参数传递的方法。此方法使用 PHP "instanceof" 快捷方式。
//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 {
//...
}
}
}
使用 isset() 会引发错误。我希望它工作的方式是将 $pc 参数 rotate($a, PointCartesien $pc = SOMETHING) 默认设置为 (0,0) 。我该怎么做?
【问题讨论】:
-
$pc在方法定义中没有默认值,所以它是必需的参数,在方法调用中不指定它只会是一个致命错误。尝试rotate($a, $pc = null),然后稍后进行显式isnull()测试,并在必要时创建您的0,0 对象。