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 :)

3
  • 1
    What does this symbol mean in PHP? Commented Jun 25, 2014 at 14:57
  • Start from here Commented Jun 25, 2014 at 14:58
  • 1
    Depends on your use case where you may want to access said properties Commented Jun 25, 2014 at 15:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.