Solved

$stefan->name vs $stefan->get_name();

Posted on 2013-11-26
13
243 Views
Last Modified: 2013-11-29
http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-3.php



Step 12:
Directly accessing properties - don't do it!
You don't have to use methods to access objects properties; you can directly get to them using the arrow operator (->) and the name of the variable.
For example: with the property $name (in object $stefan) you could get its value like so:
$name = $stefan->name;
Though doable, it is considered bad practice to do it because it can lead to trouble down the road. You should use getter methods instead - more on that later.



why is this better


        <?php
                $stefan = new person("Stefan Mischook");
                echo "Stefan's full name: ".$stefan->get_name(); 

Open in new window

0
Comment
Question by:rgb192
  • 3
  • 2
  • 2
  • +5
13 Comments
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 39679993
<Link to external Q&A site removed>

kaufmed, Topic Advisor
0
 
LVL 29

Expert Comment

by:Paul Jackson
ID: 39680038
Imagine you wanted to change the way the property value is processed, if you have accessed it using the property name you will have to change it at each point you retrieve the property value. If you retrieve the property using the getter method, you will only have to change the processing in the getter method.
0
 
LVL 1

Assisted Solution

by:gwnet
gwnet earned 50 total points
ID: 39680080
Hi
You have explanation :
http://php.net/manual/en/language.oop5.visibility.php


See examples...
0
 
LVL 34

Assisted Solution

by:Dan Craciun
Dan Craciun earned 50 total points
ID: 39680464
Standard OOP best practices requires objects to be "black boxes", which means they should not disclose directly their properties.

Suppose for now you have your stefan class/object, and you use it in 5000 calls. And your colleagues use your stefan class, that you proudly created, in their projects.

Your supervisor comes and tells you you have to split the name property in "firstname" and "lastname", and delete the former "name" property.

What do you do then?
a. You used to call directly your property (stefan->name): You do have the option of looking for another job.

b. you used a getter: you simply replace "return $name" with "return $firstname + $lastname"

HTH,
Dan
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 50 total points
ID: 39680869
$stefan->name vs $stefan->get_name();
$stefan->name is a reference to the name property of the $stefan object.  $stefan->get_name() is a reference to the get_name() method of the $stefan object.  Whenever you see parentheses at the end of a PHP variable name, with or without arguments inside them, you know you're looking at a reference to a function.  If the name is preceded by the -> you know you're looking at a method of an instantiated object.
0
 

Author Comment

by:rgb192
ID: 39681752
>>

What do you do then?
a. You used to call directly your property (stefan->name): You do have the option of looking for another job.

b. you used a getter: you simply replace "return $name" with "return $firstname + $lastname"



and



Imagine you wanted to change the way the property value is processed, if you have accessed it using the property name you will have to change it at each point you retrieve the property value. If you retrieve the property using the getter method, you will only have to change the processing in the getter method.




I dont understand how the getter method can be used by many coders but the property is only one value
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 29

Assisted Solution

by:Paul Jackson
Paul Jackson earned 50 total points
ID: 39681833
You write a class, in this class for an object you make the properties public then in your code that uses that object you access the objects properties directly in many places in the code. Now this will work fine but somewhere down the line, someone comes to you and wants to change how the property is returned, could be something as simple as formatting change or another value appended to it as in the firstname + lastname example rgb192 gives.
Now because you are accessing the object property directly in your code you will have to go to each of these places in the code and change the way the property value is returned.
If you had used a getter method, you only have to change the code in the getter method to change the way the property is returned rather than all the places you access the object property in your code.

The object property value is just that a singular value, in the getter method you get the property method and then modify it, format it, append a prefix etc etc before it is returned to the calling code.

If you like it is simpler to follow the simple rule that all an objects properties should be private to its class, and a getter/setter methods should be used to read/change the value.
In most cases the getter/setter will just be returning the property value without changing it, and it may seem that initially it seems like you're writing a lot of additional code writing the getter/setter methods rather than accessing the properties directly.
However from a maintenance point of view, when you get a change of requirement come in that requires how the property value is returned changes in some way then you only have to change the getter/setter method rather than track down in code all the places that the property value is used and initiate the change in all those places.

Hope that helps
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 250 total points
ID: 39681846
It's about maintainability. Think about it like this:  Say you have a class Person, and that class exposes two properties called firstName and lastName (with hard-coded data for demonstration only):

class Person
{
    public $firstName = 'John';
    public $lastName = 'Public';
}

Open in new window


Now let's say you start using that class all over your code:

<?php

    $johnP = new Person();

    echo "Hello" . $johnP->firstName . " " . $johnP->lastName;

?>

Open in new window


This is just one place, but imagine that you've scattered logic similar to this in 100 pages on your site. Now assume that a new business requirement comes in:  the Marketing department determines that people really like having their middle initial shown to them on your site. How do you make that happen. Certainly, you could modify your class:

class Person
{
    public $firstName = 'John';
    public $lastName = 'Public';
    public $middleInitial = "Q";
}

Open in new window


...and then make changes in all places. But how many places are there? If you scattered it throughout 100 pages of your site, then you have 100 places to change. Are you going to remember all 100 places 6 months from now? If you instead created a new getter on your class:

class Person
{
    public $firstName = 'John';
    public $lastName = 'Public';
    public $middleInitial = "Q";

    public function getFullName() {
        return $firstName . " " . $middleInitial . " " . $lastName;
    }
}

Open in new window


...along with the new middle initial property, you can use this getter in 100 places instead of the concatenation logic that I demonstrated earlier. Why is this better? Well, take your 100 places of code, and change them to something like:

<?php

    $johnP = new Person();

    echo "Hello" . $johnP->getFullName();

?>

Open in new window


Now you have a contract for your class. It should rarely (if ever) change. Now 100 places of code don't have to change if management decides to remove the middle initial from the name, only one does:  the new getter that you added.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39681872
Note on private properties.  They may make it impossible to extend the class if they're used incorrectly.  Some of this is art and some of it is science.  My "default" position absent any clear reason to do otherwise is protected properties and public methods.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 39682153
@Ray_Paseur

Note on private properties.  They may make it impossible to extend the class if they're used incorrectly.
Is this a "feature" of PHP? I know in C# that while you cannot access a base class' private fields (equivalent to PHP's property; "property" means something else in C#), you can access any protected or public fields, properties, or methods on the base class from the child class (due to inheritance). Could you not do the same in PHP, that is, access the private property via a base class' public or protected getter/setter?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39682188
Yes, I think you could call this a feature with quotation marks.  You can access private properties via getters and setters only.  If you extend the base class, the child class inherits all of the non-private fields (properties in PHP parlance) and methods.  The child class can redefine and override the base class methods.  This sort of makes me wonder what would happen if you had a base class with a private property and a protected setter.  In the child class it overrides the setter method.  I expect it would fail, but I've never tried something like that.
0
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 50 total points
ID: 39682831
greetings rgb192, you have read this - "it is considered bad practice to do it because it can lead to trouble down the road", , but this and all code work that you do in a CLASS for the properties like -
public $name;

and the methods like -
public function get_name() {

depend on the code that YOU write in that class, and the code that you write outside of the class to Initialize and Use that Class in your web page.
So in your example you ask "why is this better" -
$stefan->get_name();

it is not better or worse at this point in your code write! ! ! And you will have no problems using instead -
echo $stefan->name;

BUT, it may become better or worse as you add hundreds and hundreds of lines of code to your Class to do more and more difficult things and calculations, with hundreds of more informations besides just a simple $name. . . .
So no code in a class is better or worse, Until YOU write code that is "worse" or does not work correctly, and then rewrite that "worse" code to work, , so it is becomes Better code.
At this point in your Class learning, you may not really get any understanding about such a general statement like "it is considered bad practice to do" and I can not tell you that using properties like -
echo $products->vin_ID;
is bad, because I do it all the time and it works, however if I do the reverse
$products->vin_ID = "deck31vin72h8kl4";
then that would cause problems in that products class!, but I know NOT to do that and only read the vin_ID. But all class code to work correctly, depends on what you write in that Class, not so much on any general advice like  "it is considered bad practice to do".
0
 

Author Closing Comment

by:rgb192
ID: 39685476
After reading about marketing wanting to add middle name to to name, I understand the other experts.  So this is the best answer for me.

Thank you all.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now