0

Hi! I have a question regarding a problem I've faced dealing with object oriented PHP. I'm used to always return a value after a method has been executed and then use the returned value in other methods. But that's because I've always done that in procedural programming. So I wonder if it's normal practice to instead use the properties of the class and use $this to retrieve those values in the different methods instead of passing them as parameters? What is best and how should I do?

code example. This:

class example {
   function __construct($param){
      $result = $this->foo($param);
      $result2 = $this->bar($result);
      ...
   }

   function foo($param) ...
   function bar($param) ...
}

or this:

class example {
   var $prop;

   function __construct($param){
      $this->prop = $param;
      $this->foo();
      $this->bar();
      ...
   }

   function foo() ...
   function bar() ...
}

Do you understand my example? :)

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by gunnarflax
1

It is a question of code efficiency. You use functions 1) to avoid code repetitions and 2) to make the semantics clearer. If the function is only called one during initialization and you will not use the result at another place, don't store it in a property. If on the other hand the function will be called more than once it is good practice to store the result for re-usage, especially if this is a costly function.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.