Jump to content

Using functions with arguments in classes?


Wuhtzu

Recommended Posts

Hey

 

I was just wondering if it's acceptable to declare functions, which takes arguments, inside a class? By acceptable I mean if it's good/acceptable or bad coding practice.

 

Here is an example:

 

Without arguments:

<?PHP

class SomeClass {

  var $a;
  var $b;
  var $ECHO_OUTPUT = false;

  function some_function(){
    $a = $this->a;
    $b = $this->b;
    $ECHO_OUTPUT = $this->ECHO_OUTPUT;

    $result = $a + $b;

    if($ECHO_OUTPUT) {
      echo $result;
    }
    else {
      return $result
    }
  }

}

//Usage
$some_class = new SomeClass();
$some_class->a = 2;
$some_class->b = 2;
$some_class->ECHO_OUTPUT  = true;

$some_class->some_function();

?>

 

 

Width arguments:

<?PHP

class SomeClass {

  var $a;
  var $b;

  function some_function($ECHO_OUTPUT = false){
    $a = $this->a;
    $b = $this->b;

    $result = $a + $b;

    if($ECHO_OUTPUT) {
      echo $result;
    }
    else {
      return $result
    }
  }

}

//Usage
$some_class = new SomeClass();
$some_class->a = 2;
$some_class->b = 2;

$some_class->some_function(ECHO_OUTPUT);

?>

 

I know this isn't pretty or advanced in any way but just an example. The arguments I'm having "concerns" about is primarily flags. For some reason i feels weird to set/pass flags as $some_class->SOME_FLAG = true; but on the other hand I haven't come across many classes which uses arguments with it's functions.

 

So I would like to know what you think about the two methods, both regarding how to get around flags for class functions and the use of arguments for class functions in general :)

 

 

Best regards

Wuhtzu

 

Link to comment
Share on other sites

both work, but id think that the only real reason to pass vars in the function declaration (most of the time) is for static methods that you'll want to access without instantiating the class or for methods that are available to children/parent classes

 

so if some_function() was just a block of code used by your class and nothing else, then there is no real advantage (that i know of), with doing the second way.

 

just my thoughts

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.