我有这门课
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;
?>
我无法理解如何为私有(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/