gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:22:37 25 4
gpt4 key购买 nike

我有这门课

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/

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