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? :)

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.

Thank you for your answer, It made it all a bit clearer :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.