private modifier in php doesn' work like expected

Viewed 60

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;

?>

the result like this: enter image description here

I cannot understand how could I assign value to private variable ?

2 Answers

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.

Actually the display of 2000 does not mean that the parent class value is set.

Your statement only creates a new variable for the class itself, not for the parent class because the price2 is not declared as protected / public.

It explains why the system does not throw an error in your case

Recap:

  • public scope to make that property/method available from anywhere, other classes and instances of the object.

  • private scope when you want your property/method to be visible in its own class only.

  • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class

Try create a method (say setPrice) to set the price2 in the parent class if you need to set a value for this private variable

<?php
class Product {
   private $price2;

   function setPrice($a) {
     $this->price2 = $a;
   }

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

class Banana extends Product {
   }


$ba = new Banana();

//$ba->price2 = 2000; 

/*The above will not throw an error even executed 
because it is creating a property within 
the banana class*/

$ba->setPrice(2001);

echo $ba->getPrice();

/*The above is for setting / getting 
the price2 private variable 
in the parent class-just for illustration*/

?>
Related