0

Possible Duplicate:
PHP OOP: Unique method per argument type?
PHP 5.3 method overloading (like in Java)

I have some different class like users and groups. I want to create a general class to add attribute of the class. My class has some function like add, delete, edit and etc. for example:

<?php
class Persistence{
    function add(Users $userObj){
        ....
    }
    function add(Groups $groupObj){
        ....
    }
}
?>

How can I do this?

Community
  • 1
  • 1
Mahdi Mojiry
  • 21
  • 1
  • 4

5 Answers5

5

While type hinting is allowed in PHP, method overloading based on argument types is not. So you need to create different methods for each of your cases and use these instead. What you can do, however, is drop the type hinting from the add-method, and use if-else statements or a switch on the argument instead:

public function add ($collection) }
   if($collection instanceof Users) {
     return $this->addUsers($collection);
   }
   if($collection instanceof Groups) {
     return $this->addGroups($collection);
   }
   ...
   throw new InvalidArgumentException("Unknown collection type");
}

public function addUsers(Users $users) {
}

public function addGroups(Groups $groups) {
}
PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
2

Method overloading like this is not possible; you have to weaken the predicate in the declaration:

function add($obj)
{
    if ($obj instanceof Users) {
    } elseif ($obj instanceof Groups) {
    } else {
        throw new Exception("Invalid type for object");
    }
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

An alternative solution is to create an interface for your Persistence class:

interface PersistenceInterface { /* ... */ }

class Users implements PersistenceInterface { /* ... */ }
class Groups implements PersistenceInterface { /* ... */ }

class Persistence
{
    public function add(PersistenceInterface $userObj)
    {
        // ...
    }
}

This way, only objects marked with the interface are allowable by your Persistence class.

noetix
  • 4,773
  • 3
  • 26
  • 47
0

In PHP, overloading is only for properties and not as you might be used to from other languages. You could overload __call and __callStatic, but it is simpler to employ inheritance.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

PHP does not have typed parameters, so you wouldn't be able to do it like in your example. You could pass in a second parameter with the type however and use that within the function:

function add($type, $object){
    if ($type=="user"){
       // process $object as a user
    } elseif ($type=="group"){
       // process $object as a group
    }
}
doublesharp
  • 26,888
  • 6
  • 52
  • 73