gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:12:00 26 4
gpt4 key购买 nike

我的 php 5.3 有一个奇怪的行为

我有一个类在一个函数中加入了这个

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

但是函数 cacheInstance 是一个私有(private)函数....

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

有人可以解释一下为什么可以这样使用吗?这种方法不应该是私有(private)的,也就是从外部无法访问的吗?

更新:

好吧,现在我完全迷失了......我什至可以访问实例的私有(private)变量......就像什么......这必须是一些预期的行为,有人能给我指明方向吗?

最佳答案

如果您可以使用 new self() 创建类实例,则意味着您在该类中,当然您可以访问私有(private)属性和函数。此片段摘自 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

关于php - $new = new self($data);有私有(private)函数甚至变量oO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32882729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com