PHP similar methods in different classes, but different varaible member capabilities?

I have two classes that are similar but have different capabilities for member variables. I will reduce it to

class LimitedADAData{
       private $member;
       public function mapMember($map){
           //use $this->member with $map      
       }
}
class ADAData{
       public $member;
       public function mapMember($map){
          //use $this->member with $map
       }
}

      

Do traits, interfaces and abstract classes have to declare scope? So what do you do when the reusable methods don't care what the scope of the variable is, but the rest of the class does?

For example, by doing this ...

interface DataMethods{
    public $member;
    public function mapMember($map);
 }

      

... not good for LimitedADAData which has a private $ member

But leaving the variable

interface DataMethods{
    public function mapMember($map);
 }

      

bad because the mapMember function looks for the $ member variable, so I am not actually accounting for the dependency.

+3


source to share


1 answer


From manual :

All methods declared in the interface must be public; it is the nature of the interface.

It is not possible to declare properties on interfaces, that is not their purpose.
If you do this, you will receive:

 Fatal error: Interfaces may not include member variables

      



I would recommend reading the top comment on the man page above: http://php.net/manual/en/language.oop5.interfaces.php#107364

The interface doesn't care about the implementation of the method at all, it's just a contract that defines what the implementation classes should do with their public methods. What public or private methods or properties are used by a class to fulfill the contract is irrelevant to the interface.

You are not giving up a dependency, by omitting a property in your interface, you are leveraging an abstraction.

+2


source







All Articles