Sign up ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

I am practicing OOP with PHP, and I am struck at setter and getter methods.

I can directly access the class properties and methods with getter method then what's the use of setter method?

See my example.

class MyClass{
    public $classVar = "Its a class variable";
    public function Getter(){
        return $this -> classVar;
$obj = new MyClass;
echo $obj -> Getter();
share|improve this question
If you don't need to set the property from outside the object's scope, then you don't need a setter. – Yannis Sep 17 '12 at 12:16
if u make a property public then you are exposing the internals of your class which will make your code depends on "How" the class does something instead of "What" it does. – Songo Sep 17 '12 at 12:31

1 Answer 1

up vote 10 down vote accepted

Your class variable $classVar shouldn't be public.

One of the reasons for having getters and setters is to hide your implementation. By making the class variable public you are exposing your implementation thus negating this benefit.

Make the variable private.

share|improve this answer
You mean to say its the concept of Encapsulation. Hiding the implementation. – phphunger Sep 17 '12 at 12:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.