什么时候以及为什么我应该在类中使用公共、私有和受保护的函数和变量?它们之间的区别是什么?

例子:

// Public
public $variable;
public function doSomething() {
  // ...
}

// Private
private $variable;
private function doSomething() {
  // ...
}

// Protected
protected $variable;
protected function doSomething() {
  // ...
}

当前回答

又提了一个老问题,但我认为从你所定义的API的角度来考虑这个问题是一个很好的方法。

public——所有标记为public的东西都是API的一部分,任何使用你的类/接口/其他的人都会使用和依赖它。 protected -不要被愚弄了,这也是API的一部分!人们可以子类化,扩展你的代码,使用任何标记为受保护的东西。 private -私有属性和方法可以随心所欲地更改。没有其他人可以使用这些。这些是唯一可以在不进行破坏性更改的情况下进行更改的内容。

或者用Semver的话说:

对任何公共或受保护的内容的更改都应被视为重大更改。 任何新的公开或受保护的内容(至少)都应该是MINOR 只有对任何私有内容的新/更改才能被PATCH

因此,在维护代码方面,注意哪些内容是公开的或受保护的,因为这些是你向用户承诺的内容。

其他回答

对我来说,这是理解这三种属性类型最有用的方法:

Public:当您可以在代码中的任何地方直接访问和更改此变量时,使用此选项。

类外部的示例用法:

$myObject = new MyObject()
$myObject->publicVar = 'newvalue';
$pubVar = $myObject->publicVar;

Protected:当你想强迫其他程序员(和你自己)在访问和设置变量时在类外部使用getter /setter时使用这个选项(但你应该保持一致,在类内部也使用getter和setter)。This或private往往是设置所有类属性的默认方式。

为什么?因为如果你决定在未来的某个时候(可能甚至在5分钟内),你想要操作该属性返回的值,或者在获取/设置之前对它做一些事情,你可以这样做,而无需重构你在项目中使用它的所有地方。

类外部的示例用法:

$myObject = new MyObject()
$myObject->setProtectedVar('newvalue');
$protectedVar = $myObject->getProtectedVar();

Private:私有属性与受保护属性非常相似。但显著的特点/区别是,将其设为私有也使得子类无法访问它,而无需使用父类的getter或setter。

因此,基本上,如果你正在为一个属性使用getter和setter(或者如果它只在父类内部使用,并且它并不意味着在其他任何地方都可以访问),你最好将它设置为私有,只是为了防止任何人试图直接使用它并引入错误。

在子类(扩展MyObject)中的使用示例:

$this->setPrivateVar('newvalue');
$privateVar = $this->getPrivateVar();

公众:

当你将一个方法(函数)或属性(变量)声明为public时,这些方法和属性可以通过以下方式访问:

声明它的类。 继承上述声明类的类。 这个类之外的任何外部元素也可以访问这些东西。

例子:

<?php

class GrandPa
{
    public $name='Mark Henry';  // A public variable
}

class Daddy extends GrandPa // Inherited class
{
    function displayGrandPaName()
    {
        return $this->name; // The public variable will be available to the inherited class
    }

}

// Inherited class Daddy wants to know Grandpas Name
$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Prints 'Mark Henry'

// Public variables can also be accessed outside of the class!
$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Prints 'Mark Henry'

保护:

当将方法(函数)或属性(变量)声明为受保护时,可以通过

声明它的类。 继承上述声明类的类。

外部成员不能访问这些变量。“局外人”的意思是它们不是所声明类本身的对象实例。

例子:

<?php

class GrandPa
{
    protected $name = 'Mark Henry';
}

class Daddy extends GrandPa
{
    function displayGrandPaName()
    {
        return $this->name;
    }

}

$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Prints 'Mark Henry'

$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error

准确的错误是这样的:

PHP致命错误:无法访问受保护的属性GrandPa::$name


私人:

当你将一个方法(函数)或属性(变量)声明为私有时,这些方法和属性可以通过以下方式访问:

声明它的类。

外部成员不能访问这些变量。在某种意义上,它们不是已声明类本身的对象实例,甚至不是继承已声明类的类。

例子:

<?php

class GrandPa
{
    private $name = 'Mark Henry';
}

class Daddy extends GrandPa
{
    function displayGrandPaName()
    {
        return $this->name;
    }

}

$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Results in a Notice 

$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error

准确的错误消息将是:

注意:Undefined属性:Daddy::$name 致命错误:无法访问私有属性GrandPa::$name


使用反射解剖爷爷类

这个主题并没有超出范围,我在这里添加它只是为了证明反射是非常强大的。正如我在上面三个例子中所述,受保护的和私有的成员(属性和方法)不能在类之外被访问。

然而,有了反射,你甚至可以在类外部访问受保护的和私有的成员。

什么是反射?

反射增加了逆向工程类、接口、 函数、方法和扩展。此外,他们还提供了一些方法 检索函数、类和方法的文档注释。

序言

我们有一个名为Grandpas的类,我们有三个属性。为了便于理解,假设有三个有名字的爷爷:

马克亨利 约翰冲突 将琼斯

让我们将它们(指派修饰符)分别设为public、protected和private。您非常清楚,protected成员和private成员不能在类外部访问。现在让我们用反射来反驳这个说法。

的代码

<?php

class GrandPas   // The Grandfather's class
{
    public     $name1 = 'Mark Henry';  // This grandpa is mapped to a public modifier
    protected  $name2 = 'John Clash';  // This grandpa is mapped to a protected  modifier
    private    $name3 = 'Will Jones';  // This grandpa is mapped to a private modifier
}


# Scenario 1: without reflection
$granpaWithoutReflection = new GrandPas;

# Normal looping to print all the members of this class
echo "#Scenario 1: Without reflection<br>";
echo "Printing members the usual way.. (without reflection)<br>";
foreach($granpaWithoutReflection as $k=>$v)
{
    echo "The name of grandpa is $v and he resides in the variable $k<br>";
}

echo "<br>";

#Scenario 2: Using reflection

$granpa = new ReflectionClass('GrandPas'); // Pass the Grandpas class as the input for the Reflection class
$granpaNames=$granpa->getDefaultProperties(); // Gets all the properties of the Grandpas class (Even though it is a protected or private)


echo "#Scenario 2: With reflection<br>";
echo "Printing members the 'reflect' way..<br>";

foreach($granpaNames as $k=>$v)
{
    echo "The name of grandpa is $v and he resides in the variable $k<br>";
}

输出:

#Scenario 1: Without reflection
Printing members the usual way.. (Without reflection)
The name of grandpa is Mark Henry and he resides in the variable name1

#Scenario 2: With reflection
Printing members the 'reflect' way..
The name of grandpa is Mark Henry and he resides in the variable name1
The name of grandpa is John Clash and he resides in the variable name2
The name of grandpa is Will Jones and he resides in the variable name3

常见的误解:

请不要与下面的例子混淆。正如您仍然可以看到的,如果不使用反射,就不能在类外部访问private和protected成员

<?php

class GrandPas   // The Grandfather's class
{
    public     $name1 = 'Mark Henry';  // This grandpa is mapped to a public modifier
    protected  $name2 = 'John Clash';  // This grandpa is mapped to a protected modifier
    private    $name3 = 'Will Jones';  // This grandpa is mapped to a private modifier
}

$granpaWithoutReflections = new GrandPas;
print_r($granpaWithoutReflections);

输出:

GrandPas Object
(
    [name1] => Mark Henry
    [name2:protected] => John Clash
    [name3:GrandPas:private] => Will Jones
)

调试功能

Print_r、var_export和var_dump是调试器函数。它们以人类可读的形式呈现关于变量的信息。这三个函数将显示PHP 5中对象的受保护属性和私有属性。静态类成员将不会显示。


更多资源:

PHP手册- OOP属性 PHP手册- OOP可见性 PHP类的可见性 Jordizle.com - Public, Private,在PHP 5中受保护


PHP中的变量有三种类型:

Public:该变量类型的值在所有范围内可用,并在代码执行时调用。 声明为:public $ examschedule;

Private:此类型变量的值仅在它所属的类上可用。 私人classRoomComputers美元;

Protected:该类的值仅且仅在以继承或其子类的形式授予Access时可用。通常使用::授予父类访问权限

保护familyWealth美元;

又提了一个老问题,但我认为从你所定义的API的角度来考虑这个问题是一个很好的方法。

public——所有标记为public的东西都是API的一部分,任何使用你的类/接口/其他的人都会使用和依赖它。 protected -不要被愚弄了,这也是API的一部分!人们可以子类化,扩展你的代码,使用任何标记为受保护的东西。 private -私有属性和方法可以随心所欲地更改。没有其他人可以使用这些。这些是唯一可以在不进行破坏性更改的情况下进行更改的内容。

或者用Semver的话说:

对任何公共或受保护的内容的更改都应被视为重大更改。 任何新的公开或受保护的内容(至少)都应该是MINOR 只有对任何私有内容的新/更改才能被PATCH

因此,在维护代码方面,注意哪些内容是公开的或受保护的,因为这些是你向用户承诺的内容。

考虑到“时”: 如果我不太确定,我倾向于一开始就把所有东西都声明为私有。原因是,将私有方法转换为公共方法通常比将私有方法转换为公共方法容易得多。这是因为您至少可以确定private方法除了在类本身中没有在其他地方使用过。一个公共方法可能已经在各处使用,可能需要大量重写。

更新:我现在使用默认的protected,因为我发现它对于封装来说已经足够好了,并且当我扩展类的时候(无论如何我都尽量避免)它不会妨碍到我。只有当我有充分的理由使用另外两个时,我才会使用。

使用私有方法的一个很好的理由是,它实现了对象固有的一些东西,即使是扩展类也不应该更改(除了封装之外,还有像内部状态管理这样的事实原因)。最终,它仍然很容易追踪到一个受保护的方法通常在哪里被使用,所以我现在默认为受保护。我承认,也许不是百分百客观的“战壕”经验。