如何在 PHP 中判断点是否位于圆内

本文详解如何使用面向对象方式在 php 中实现点与圆的位置关系判断,重点解决方法调用错误、作用域缺失及逻辑完整性问题,并提供可直接运行的修复代码。

在几何计算中,判断一个二维点是否位于给定圆的内部(含边界)是一个经典问题。其数学原理基于欧几里得距离:若点 $ P(x_p, y_p) $ 到圆心 $ C(x_c, y_c) $ 的距离小于等于半径 $ r $,即
$$ (x_p - x_c)^2 + (y_p - y_c)^2 \leq r^2 $$
则该点在圆内(或圆上)。PHP 实现需严格遵循面向对象规范,尤其注意实例方法调用必须通过对象引用($this 或具体对象变量),不可省略。

以下是修复后的完整代码(已优化命名、添加注释与健壮性处理):

x = $x;
        $this->y = $y;
    }

    public function getX(): float { return $this->x; }
    public function getY(): float { return $this->y; }
}

class Circle {
    private float $centerX;
    private float $centerY;
    private float $radius;

    public function __construct(float $centerX, float $centerY, float $radius) {
        if ($radius < 0) {
            throw new InvalidArgumentException("Radius must be non-negative.");
        }
        $this->centerX = $centerX;
        $this->centerY = $centerY;
        $this->radius = $radius;
    }

    public function getCenterX(): float { return $this->centerX; }
    public function getCenterY(): float { return $this->centerY; }
    public function getRadius(): float { return $this->radius; }

    /**
     * Checks whether the given point lies inside or on the boundary of this circle.
     * Uses squared distance comparison to avoid floating-point sqrt() and improve performance.
     */
    public function containsPoint(Point $point): bool {
        $dx = $point->getX() - $this->getCenterX();
        $dy = $point->getY() - $this->getCenterY();
        $squaredDistance = $dx * $dx + $dy * $dy;
        $squaredRadius = $this->getRadius() * $this->getRadius();

        return $squaredDistance <= $squaredRadius;
    }
}

使用示例(index.php):

containsPoint($point)) {
    echo "✅ Point (3, 4) is inside or on the circle.\n";
} else {
    echo "❌ Point (3, 4) is outside the circle.\n";
}

// 验证边界情况:点在圆心正右方 10 单位处 → 应返回 true(在圆上)
$boundaryPoint = new Point(20, 10);
var_dump($circle->containsPoint($boundaryPoint)); // bool(true)

⚠️ 关键修正说明:

  • 原 checkIfInside() 方法未声明参数,导致无法访问外部 Point 实例;修复后明确接收 Point $point 参数。
  • 所有方法调用均添加 $this->(如 $this->getCenterX())或对象变量前缀(如 $point->getX()),杜绝“undefined function”错误。
  • 使用
  • 引入类型声明(float)、异常校验(负半径拦截)和 PHPDoc 注释,提升代码可靠性与可维护性。
  • 方法名重构为 containsPoint(),语义更清晰,符合 PSR-12 命名规范。

总结:几何判断类应聚焦单一职责——封装计算逻辑,将数据(点/圆)作为参数传入,而非隐式依赖全局或未定义上下文。此模式既保障封装性,又便于单元测试与复用。