php - php 中的 private 修饰符不能像预期的那样工作

标签 php private access-modifiers

我有这门课

class Product {
    public $name;
    private $price2;
    protected $number;

function getNmae() {
    return $this->name;
}

function getPrice() {
    return $this->price2;
}

function getNumber() {
    return $this->number;
}
}

在这里我可以毫无问题地使用私有(private)价格吗?

<?php
include 'oop_test.php';

class Banana extends Product {
   
   
}


$ba = new Banana();
echo $ba->price2 = 2000;

?>

结果是这样的: enter image description here

我无法理解如何为私有(private)变量赋值?

最佳答案

在这种情况下,您似乎已经即时创建了一个属性。一个简化的样本显示了这一点:

<?php
class Product {
    private $price2;

    function getPrice() {
        return $this->price2;
    }
}

class Banana extends Product {}


$ba = new Banana();
$ba->price2 = 2000;

echo 'On the fly property: ' . $ba->price2;
echo 'Private property: ' . $ba->getPrice();

该代码为属性 price2 打印 2000,但是 getPrice 没有返回任何内容 - 所以您还没有真的Product 类上编写了属性 price2,但在 Banana 类中创建了一个新属性。

这里不涉及 Product 类中的“原始”属性,因为它是一个私有(private)属性,因此在 Banana 类中根本不可用。

关于php - php 中的 private 修饰符不能像预期的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73658719/

相关文章:

c# - 为什么 sealed 关键字不包含在访问修饰符列表中?

php - 根据下拉选择自动填充文本字段,其中所有值都来自 MYSQL 表

javascript - Uncaught TypeError : $(. ..).value is not a function when trying to send a value via JQuery

SEO:安全页面和 rel=nofollow

python - 'exec' 不适用于私有(private)方法 Python

c++ - 访问 "this"对象以外的 protected 成员

php - sql查询连接三个表

php - Xampp 服务器中的所有 php 项目应该放在哪里?

c++ - C++ 类的私有(private)成员和 protected 成员有什么区别?

java - Java中的public int和int有什么区别?