Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7029011
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T00:28:54+00:00 2026-05-28T00:28:54+00:00

What’s considered best practice writing OOP classes when it comes to using a property

  • 0

What’s considered best practice writing OOP classes when it comes to using a property internally.

Consider the following class;

<?php
Class Foo
{
    /**
     * @var null|string
     */
    protected $_foo;

    /**
     * @return null|string
     */
    public function getFoo()
    {
        return $this->_foo;
    }

    protected function _doSomething()
    {
        $foo    = $this->_foo;
        $result = null;
        // ...
        return $result;
    }
}

As you see im using the property _foo in _doSomething() although a sub-class could override getFoo() returning a computed value not stored back into _foo; that’s a flaw.

What should i do?

  1. mark getter as final, use property internally (no extra function calls, enforce end-developer to use _foo as a property since it’s protected)
  2. use getFoo() internally, mark _foo as private (extra function calls)

Both options are waterproof however im seriously concerned about all the extra function calls so i tend to use option 1 however option 2 would be more “true OOP” imho.

Also read http://fabien.potencier.org/article/47/pragmatism-over-theory-protected-vs-private which also suggests option 2 :/

Another related question;
If a property has a setter should that property be private, enforcing end-developers to use it in sub-classes or should it be an unwritten rule the programmer is responsible to set a valid property value?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T00:28:54+00:00Added an answer on May 28, 2026 at 12:28 am

    The second approach is, as you say, the more correct way according to OOP. You’re also right that there is more cost in terms of CPU cycles in calling a method than in accessing a property as a variable. However, this will in most cases fall into the category of a micro-optimization. It won’t have a noticeable effect on performance except if the value in question is being used heavily (such as in the innermost part of a loop). Best practice tends to favour the correct over the most performant unless the performance is genuinely suffering as a result of it.

    For simple variables the use of a getter internally is not immediately obvious, but the technique comes into its own if you’re dealing with a property that gets populated from an external data source such as a database. Using the getter allows you to fetch the data from the DB in a lazy way, ie on demand and not before it’s needed. For example:

    class Foo
    {
        // All non-relevent code omitted
        protected $data = NULL;
    
        public class getData ()
        {
            // Initialize the data property
            $this -> data = array ();
            // Populate the data property with a DB query
            $query = $this -> db -> prepare ('SELECT * FROM footable;');
            if ($query -> execute ())
            {
                $this -> data = $query -> fetchAll ();
            }
            return ($this -> data);
        }
    
        public function doSomethingWithData ()
        {
            $this -> getData ()
            foreach ($this -> data as $row)
            {
                // Do processing here
            }
        }
    }
    

    Now with this approach, every time you call doSomethingWithData the result is a call to getData, which in turn does a database query. This is wasteful. Now consider the following similar class:

    class Bar
    {
        // All non-relevent code omitted
        protected $data = NULL;
    
        public class getData ()
        {
            // Only run the enclosed if the data property isn't initialized
            if (is_null ($this -> data))
            {
                // Initialize the data property
                $this -> data = array ();
                // Populate the data property with a DB query
                $query = $this -> db -> prepare ('SELECT * FROM footable;');
                if ($query -> execute ())
                {
                    $this -> data = $query -> fetchAll ();
                }
            }
            return ($this -> data);
        }
    
        public function doSomethingWithData ()
        {
            foreach ($this -> getData () as $row)
            {
                // Do processing
            }
        }
    }
    

    In this version, you can call doSomethingWithData (and indeed getData) as often as you like, you will never trigger more than one database lookup. Furthermore, if getData and doSomethingWithData are never called, no database lookup is ever done. This will result in a big performance win, as database lookups are expensive and should be avoided where possible.

    It does lead to some problems if you’re working in a class that can update the database, but it’s not hard to work around. If a class makes updates to its state, then your setters can simply be coded so that they null their associated state on success. That way, the data will be refreshed from the database the next time a getter is called.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
this is what i have right now Drawing an RSS feed into the php,
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I have thousands of HTML files to process using Groovy/Java and I need to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.