0

What is the proper way of accessing private/protected variable in a class in PHP?

I learned that it can be access using __construct function. Ex.

class helloWorld
{
    public $fname;
    private $lname;
    protected $full;
    function __construct()
    {
        $this->fname = "Hello";
        $this->lname = "World";
        $this->full = $this->fname . " " . $this->lname;
    }
}

Or create a Getter or Setters function. I don't know if that's the right term.

class helloWorld
{
    public $fname;
    private $lname;
    protected $full;

    function getFull(){
        return $this->full;
    }

    function setFull($fullname){
        $this->full = $fullname;
    }

}

or via __toString. I'm confuse o what should I use. Sorry, I'm still new to OOP. Also what is :: symbol in php and how can I use it?

Thanks :)

user3569641
  • 739
  • 1
  • 11
  • 38

2 Answers2

2

It is better to define your public getters and setters and only use them to get and set class properties. Then have all other functions use those getters and setters to centralize management of the properties.

Patrick
  • 3,123
  • 3
  • 25
  • 43
1

:: operator is called the scope resolution operator. It has a no.of use case.

1.Can be used to refer static variables or function of a class . the syntax is class name::variable_name Or class name::function_name() . This is because static variables or functions are referenced through class names .

2.It can also be used for function overriding. You can understand it with an example

class Base
{
    protected function myFunc() {
        echo "I am in parent class \n";
    }
}

class Child extends Base
{
    // Override parent's definition
    public function myFunc()
    {
        // But still call the parent function
        Base::myFunc();
        echo "I am in the child class\n";
    }
}

$class = new Child();
$class->myFunc();

This is useful when you want your parent function to be executed first and then your child function.

3.It is also used to refer the variables or functions within a class itself through self::$variable_name OR self::function_name() . Self is used to refer to the class itself.

Adeel Raza
  • 792
  • 5
  • 17