Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Directly Accesing property is not recommended in OOPs PHP?

Tags:

oop

php

If I have a class "person" with a property $name and its getter(get_name()) and setter(set_name()) methods, then after instantiating the objects and setting the property i.e.

$paddy = new person();

$paddy->set_name("Padyster Dave");

echo "Paddy's full name: ".$paddy->name; //WHY THIS IS NOT RECOMMENDED...

In the above code $paddy->name;WHY THIS IS NOT RECOMMENDED

EDIT

Above code is a sample code without assigning any accessifiers.. Its just to understand the $paddy->name concept

like image 258
OM The Eternity Avatar asked Apr 22 '10 05:04

OM The Eternity


3 Answers

The thing that's weird is that you have a setter, but are leaving the property public. (Assuming there's no __get magic going on.)

You usually want to use getters/setters to get more control over what can be assigned to a property and what can't. Or, you may want to execute code when the property is accessed or changed. In either case, you should force the use of the getters/setters by making the property private or protected, otherwise it's pretty pointless. It's about preventing yourself or others that will use the class from shooting their own foot.

If the setter in your example only sets the value without doing anything else, it's superfluous. If it does do something else that is required whenever the value is set, you have a flaw in your class design since it's possible to change the value without using the setter.


class Foo {
    public $bar = 0;  // is only allowed to contain numeric values
    public function setBar($val) {
        if (is_numeric($val)) {
            $this->bar = $val;
        }
    }
}

$obj = new Foo();
$obj->bar = 'some value'; // set a string, which is not allowed

If you'd make $bar protected, that wouldn't be possible.

like image 117
deceze Avatar answered Sep 23 '22 10:09

deceze


Because you might someday get rid of the $name member, replacing it with (e.g.) $first_name, $last_name and a fullname() method (not that that's a good idea). Of course, with __get and __set, it doesn't matter so much.

More generally, setting a property might not be so simple as storing a value. Giving direct access to member fields can result in other functions causing an object to be in an inconsistent state. Imagine you store an array that needs to remain sorted; if the array were public, something else could assign an unsorted array to the field.

like image 35
outis Avatar answered Sep 21 '22 10:09

outis


Exposing public fields would be a bad habit.From a good artical about OO principle in PHP

If anything changes with the object, any code that uses it needs to change as well. For instance, if the person's given, family, and other names were to be encapsulated in a PersonName object, you would need to modify all your code to accommodate the change.

like image 39
Young Avatar answered Sep 19 '22 10:09

Young