Johnny
Johnny

Reputation: 108

Reasoning behind functions like this?

Learning PHP in a OOP way and i often come across people who makes functions like this.

    public function getUsername() {
    return $this->username;
     }

Is there some security reasoning behind this? Instead of just calling the username property of the class directly? Why wrap getting a property around a function.

Upvotes: 0

Views: 41

Answers (4)

LeDoc
LeDoc

Reputation: 945

A quick reason is that you be writing a piece of code and want to prevent a user from overwriting a value in an object instance (a good example is configuration data).

Writing functions in the way you have stated also provides a standard interface which is essential when developing complex programs. It would be crazy to have a team of developers working with the one class and not defining access to variables!

Here is a good explanation of the PHP OOP basics and explains private, public and protected http://php.net/manual/en/language.oop5.basic.php

Upvotes: 0

Konstantin
Konstantin

Reputation: 566

For example you have class Test. You are using direct access to property and you have hundred place like $obj->date = 'now' etc.

class Test {
    public $date;
}

But what if you need to insert some code before updating value or modificate input value? In this case you have to find all usage of the property and update it. But if you will use getters/setters you can insert some code into them.

class Test {
    private $date;
    public getDate() { return $this->date; }
    public setDate($date) {
        // here some modification value or something else
        $this->date = $date;
    }
}

Upvotes: 0

Sougata Bose
Sougata Bose

Reputation: 31749

This type of functions are used for accessing private or protected members of class. You can not access them them directly outside of the class as they can be accessible only inside the class. So what would you do if you want to access a private member? The answer is this.

Lets take an example -

class A {
    private $x;
    public $y;
    public function test() {
        echo $this->x;
    }
}

$obj = new A();

$obj->x; // Error : You can not access private data outside the class

$obj->y; // Its fine

$obj->test(); // it will print the value of $x

Hope this will help.

Upvotes: 2

jianfyun
jianfyun

Reputation: 71

In OOP, class should hide its implementation details, and just provide necessary public functions. Users are more concerned with function rather than details.

Upvotes: 0

Related Questions