Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 256
  • Last Modified:

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

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
rgb192
Asked:
rgb192
  • 3
  • 2
  • 2
  • +5
6 Solutions
 
Marco GasiFreelancerCommented:
<Link to external Q&A site removed>

kaufmed, Topic Advisor
0
 
Paul JacksonCommented:
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
 
gwnetCommented:
Hi
You have explanation :
http://php.net/manual/en/language.oop5.visibility.php


See examples...
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Dan CraciunIT ConsultantCommented:
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
 
Ray PaseurCommented:
$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
 
rgb192Author Commented:
>>

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
 
Paul JacksonCommented:
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
 
käµfm³d 👽Commented:
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
 
Ray PaseurCommented:
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
 
käµfm³d 👽Commented:
@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
 
Ray PaseurCommented:
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
 
Slick812Commented:
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
 
rgb192Author Commented:
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

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 3
  • 2
  • 2
  • +5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now