Jump to content

Sharing function within multiple unrelated classes?


RuleBritannia

Recommended Posts

Hello

question is aimed @ experienced OOP'ers

I just wondered how you handle a function which you use in multiple classes.

You could write it fresh everytime in each class, Or make a standalone function in a php file and include it, But Im sure there is some better ways of doing this?

 

So far with research it seems some people are making static "utility" classes, which they can call without initializing.

 

Regards

Link to comment
Share on other sites

What's the function and what do you use it for (if it's not obvious)?

 

To the question, I don't actually know of any functions I'd reuse that don't clearly belong in a class...

 

Lets say you had a function which checks to see if all values in array 1 are less than all values in array 2

You may need this functionality in many different things.

 

 

 

If you can use php5.4, you might consider traits. See http://us2.php.net/traits

 

 

Will read this now, Thanks

Edited by RuleBritannia
Link to comment
Share on other sites

I'd just make a global function for it. Don't believe the people who insist on making utility classes and such: PHP is not like Java or C# where you have no choice.

 

[edit] Just by that description. If the values in these arrays are more than just mere numbers then there may be a more appropriate OOP solution (and I don't mean a utility class)...

Edited by requinix
Link to comment
Share on other sites

Lets say you had a function which checks to see if all values in array 1 are less than all values in array 2

Why do you need to do this? Is it part of a requirement? If so, then you are looking at an unidentified domain object or you are exporting business logic from the domain.

 

Who holds the values (ie array1)? Perhaps it's as simple as creating a new operation on one of your domain objects:

 

class DomainObject {
  private $array;
  
  public function isLessThan(DomainObject $o) {
    $comparator = function($a1, $a2) {
        return $a1 < $a2;
    }
    return array_search(false, array_map($comparator, $this->array, $o->array), true) === false;
  }
}
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.