gpt4 book ai didi

PHP 类的私有(private)属性和方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:38:48 26 4
gpt4 key购买 nike

注意到一些关于 PHP 类的东西,我不知道它是否是一个错误或者它为什么起作用,这是代码:

<?php
class A {
private $prop = 'value';

public function fun()
{
$obj = new A;
$obj->echoProp();
}

private function echoProp()
{
echo 'Prop has value: '.$this->prop;
}
}

$obj = new A;
$obj->fun();

结果不是我预期的错误,因为我正在调用私有(private)方法(在 PHP 5.3.10-1ubuntu3.7 上使用 Suhosin-Patch 测试)。结果是“Prop has value: value”

最佳答案

在 php 文档中 http://www.php.net/manual/en/language.oop5.visibility.php#language.oop5.visibility-other-objects它说:

Visibility from other objects

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.

所以这不是错误,而是 php 需要的功能。

关于PHP 类的私有(private)属性和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18234265/

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