Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

<?php
class MyClass{
    public $classVar = "Its a class variable";
    public function Getter(){
        return $this -> classVar;
    }
}
$obj = new MyClass;
echo $obj -> Getter();
?>
share|improve this question
2  
If you don't need to set the property from outside the object's scope, then you don't need a setter. –  Yannis Rizos 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
add comment

1 Answer

up vote 9 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
add comment

Your Answer

 
discard

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.