Home > Mobile >  private modifier in php doesn' work like expected
private modifier in php doesn' work like expected

Time:09-10

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 ?

CodePudding user response:

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.

CodePudding user response:

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.

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

Try create a method (say setPrice) to set the price2 in the parent class if you need it

<?php
class Product {
    public $name;
    private $price2;
    protected $number;

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

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

}


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

}

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

?><?php
// include 'oop_test.php';

class Banana extends Product {
   
   
}


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

echo $ba->getPrice();


?>

  • Related