Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "hide" private variable in PHP class

Tags:

php

class

I might not have a good understanding of this, but since the "username" variable is private. Shouldn't this not be a part of the return? How do I make it so the $username is private and not outputed, but the public member is?

class MyClass 
{
    private $username = "api";


    public function create_issue()
    {
        $this->public = "Joe";
        return $this;
    }

}

$test = new MyClass();
$test->create_issue();

var_dump($test);

class MyClass#1 (2) {
  private $username =>
  string(3) "api"
  public $public =>
  string(3) "Joe"
}
like image 869
KingKongFrog Avatar asked Sep 19 '26 17:09

KingKongFrog


1 Answers

I have understood your concern. First of all, let me discuss about the variable scope private. private variable is private in the current class. If you use the class in another class private variable will not work. So, you have to use an another class to protect your private variable.

<?php

class MyClassProtected 
{
    private $username = "api";
    public function doSomething(){   
    // write code using private variable
   }

}


class MyClass
{   
    public function create_issue()

    {
       $test = new MyClassProtected();
       $test -> doSomething();
       return $this->public = "Joe";
    }
}


$test = new MyClass();
$test->create_issue();
var_dump($test);

?>
like image 190
Asif Iqbal Avatar answered Sep 22 '26 06:09

Asif Iqbal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!