$new = new self($data);有私有函数甚至变量oO?

$new = new self($data); with private functions and even variables oO?

我的 php 5.3

有一个奇怪的行为

我有一个 class 把这个放在一个函数中

       $new = new self($data);
        $new->setServiceManager($this->service);
        $new->cacheInstance();

但是函数 cacheInstance 是私有函数....

private function cacheInstance()
    {
        foreach ($this->data as $name => $class) {...}
    }

谁能解释一下为什么可以这么用?这个方法不应该是私有的,也就是从外部无法访问的吗?

更新:

好的,现在我完全迷路了……我什至可以访问实例的私有变量……就像什么……这必须是某种预期的行为,有人能给我指明方向吗?

如果你可以使用 new self() 创建一个 class 实例,这意味着你在 class 中,当然你可以访问私有属性和函数。此片段摘自 PHP 文档 (link)

/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private

您的情况:

class Cache {
    private $service = null;

    private function cacheInstance()
    {
        foreach ($this->data as $name => $class) {}
    }

    public function setServiceManager( $service ) {

    }

    public function myTest( $data ) {
        $new = new self( $data );// you are in the class, so you can call new self()
        $new->setServiceManager($this->service);
        $new->cacheInstance();
    }
}
$cache = new Cache();
$cache->service; //Fatal error: Cannot access private property

$data = array();
$cache->myTest( $data );// working

$cache->cacheInstance();// not working

好的...像量子力学一样奇怪...已在 RL 中指出答案

http://php.net/manual/en/language.oop5.visibility.php

引用:

Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.

谈论奇怪...

privateprotectedpublic 可访问性适用于 class 级别,而不是对象级别。

虽然乍一看似乎有悖常理,但这并不是您通常的 PHP 怪异行为。

其他OOP语言也是如此,比如Java

Note that accessibility is a static property that can be determined at compile time; it depends only on types and declaration modifiers.

C#

The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared

(已添加亮点)

说明

可访问性是一种从其他 classes 中的 代码隐藏 实现细节 的机制,而不是用于封装对象.或者正如 Java 规范中所述,可访问性可以在编译时确定,即不会有运行时违规,因为它是一个不同的对象。

如果您看一下私有和受保护之间的区别,这是有道理的。对于私有成员,如果对象在父成员中声明,则对象无权访问自己的成员 class。听起来怪怪的?那是因为术语是错误的。 class 无法访问其 父级 class 的私有对象(即它可能不会使用它们)。

现在在您的方法中,您在同一个 class 中使用私有变量。 class 的作者,无论运行时对象是什么,都无需向自己隐藏此实现细节。