i have this class
class Product {
public $name;
private $price2;
protected $number;
function getNmae() {
return $this->name;
}
function getPrice() {
return $this->price2;
}
function getNumber() {
return $this->number;
}
}
and here I can use private price without any problem?
<?php
include 'oop_test.php';
class Banana extends Product {
}
$ba = new Banana();
echo $ba->price2 = 2000;
?>
I cannot understand how could I assign value to private variable ?
Looks like you've created a property on-the-fly in this case. A reduced sample shows this:
<?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();
That code prints 2000
for the property price2
, but nothing is returned from getPrice
- so you haven't really written the property price2
on the Product
class, but created a new one within the Banana
class.
The "original" property from the Product
class is not involved here, as it is a private property and thus not available in the Banana
class after all.