ZetCode

PHP private 关键字

最后修改于 2025 年 4 月 16 日

PHP private 关键字是面向对象编程中使用的可见性修饰符。 它将对类成员(属性和方法)的访问限制为仅在类本身内部进行。 这实现了封装。

基本定义

private 关键字使类成员无法从类外部访问。 这包括扩展父类的子类。 私有成员只能在同一类中访问。

私有可见性比 protected(允许子类访问)和 public(允许任何访问)更严格。 它是 PHP 中限制最严格的可见性修饰符。

语法:属性使用 private $propertyName;,方法使用 private function methodName() {}。 私有成员有助于防止从类外部意外修改。

基本私有属性

此示例演示了一个具有私有属性的简单类。

basic_private_property.php
<?php

declare(strict_types=1);

class BankAccount {
    private float $balance = 0.0;
    
    public function deposit(float $amount): void {
        $this->balance += $amount;
    }
    
    public function getBalance(): float {
        return $this->balance;
    }
}

$account = new BankAccount();
$account->deposit(100.50);
echo "Balance: " . $account->getBalance();

$balance 属性是私有的,不能直接访问。 我们使用公共方法与其交互。 这可以保护余额不被直接修改。 deposit 方法确保了受控访问。

私有方法

此示例显示了一个具有私有辅助方法的类。

private_method.php
<?php

declare(strict_types=1);

class User {
    private string $username;
    
    public function __construct(string $username) {
        $this->username = $this->sanitizeUsername($username);
    }
    
    private function sanitizeUsername(string $username): string {
        return trim(strtolower($username));
    }
    
    public function getUsername(): string {
        return $this->username;
    }
}

$user = new User("  Admin ");
echo "Username: " . $user->getUsername();

sanitizeUsername 方法是私有的,并在内部使用。 它在存储用户名之前对其进行处理。 外部代码不能直接调用此方法。 这隐藏了实现细节。

私有构造函数

此示例演示了使用私有构造函数来实现单例模式。

private_constructor.php
<?php

declare(strict_types=1);

class Database {
    private static ?Database $instance = null;
    
    private function __construct() {
        // Private constructor prevents direct instantiation
    }
    
    public static function getInstance(): Database {
        if (self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }
}

$db = Database::getInstance();

私有构造函数阻止使用 new 创建实例。 类通过 getInstance 控制其实例化。 这确保只存在一个实例。 这是一个常见的单例模式。

继承中的私有

此示例显示了私有成员在继承中的行为方式。

private_inheritance.php
<?php

declare(strict_types=1);

class ParentClass {
    private string $secret = "Parent secret";
    protected string $familySecret = "Family secret";
    
    public function reveal(): void {
        echo $this->secret; // Accessible here
    }
}

class ChildClass extends ParentClass {
    public function tryReveal(): void {
        // echo $this->secret; // Error: Cannot access private property
        echo $this->familySecret; // Works: protected is accessible
    }
}

$child = new ChildClass();
$child->reveal();
$child->tryReveal();

私有 $secret 在子类中不可访问。 受保护的 $familySecret 是可访问的。 这显示了私有和受保护可见性之间的区别。

私有静态属性

此示例演示了一个具有计数器的私有静态属性。

private_static.php
<?php

declare(strict_types=1);

class Counter {
    private static int $count = 0;
    
    public function __construct() {
        self::$count++;
    }
    
    public static function getCount(): int {
        return self::$count;
    }
}

new Counter();
new Counter();
new Counter();
echo "Count: " . Counter::getCount();

私有静态 $count 跟踪所有对象中的实例。 它在所有实例之间共享,但不能直接访问。 静态方法提供了对计数器的受控访问。

私有常量

此示例显示了 PHP 7.1 中引入的私有类常量。

private_constants.php
<?php

declare(strict_types=1);

class MathOperations {
    private const PI = 3.14159265359;
    
    public static function circleArea(float $radius): float {
        return self::PI * $radius * $radius;
    }
}

echo "Area: " . MathOperations::circleArea(5);
// echo MathOperations::PI; // Error: Cannot access private constant

私有常量 PI 仅在类中可访问。 它被 circleArea 方法内部使用。 常量不能被修改,但私有常量限制了它们的可访问性。

通过反射访问私有属性

此高级示例演示了使用反射访问私有属性。

reflection_private.php
<?php

declare(strict_types=1);

class SecretHolder {
    private string $secret = "Top secret";
}

$holder = new SecretHolder();
$reflector = new ReflectionClass($holder);
$property = $reflector->getProperty('secret');
$property->setAccessible(true);

echo "The secret is: " . $property->getValue($holder);

反射可以绕过私有可见性,用于测试等特殊情况。 应该谨慎使用,因为它会破坏封装。 该示例获取私有属性值,尽管它具有可见性。

最佳实践

来源

PHP 可见性文档

本教程涵盖了 PHP private 关键字,并提供了实用示例,展示了属性、方法、构造函数和常量在各种场景中的用法。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 PHP 教程