0

I do have an Interface called Jsonable.

interface Jsonabe{

public function toJson();

}

And I do have two classes implementing the interface.

class facebookTransformer implements Jsonable{

  protected $facebookHandler;

  public function __construct(){

   $this->facebookHandler = new FacebookHandler();
  }
  public function toJson(){ 

  }

}

Second class:

class googleTransformer implements Jsonable{

  protected $googleHandler;

  public function __construct(){

   $this->googleHandler = new GoogleHandler();
  }
  public function toJson(){ 

  }

}

Now with the implemented interface I know that all new classes will adhere to the interface. My question is can I somehow force all the classes implementing interface to define the property also and initalize it through constructor ? Or is it okay if I add a constructor in the interface ?

I want to make sure that all the other classes will have a $handler property.

PrStandup
  • 313
  • 1
  • 4
  • 14
  • Possible duplicate of [Do PHP interfaces have properties?](https://stackoverflow.com/questions/2756974/do-php-interfaces-have-properties) – B001ᛦ Jan 30 '18 at 14:41
  • you can have a property if you make an abstract class that implements this interface and then use that for extending the other classes, but if you want strictly interfaces then you don't have any solution for that, only to force another method that should get that, but also there you cannot be sure that will be right implemented – Edwin Jan 30 '18 at 14:45
  • @Edwin actually I was thinking about an abstract class, which it forces to have the property but still property can be null and it will crash in run-time – PrStandup Jan 30 '18 at 14:57
  • don't offer the empty constructor and force the handler to it, then you don't have this problem – Edwin Jan 30 '18 at 15:00

2 Answers2

1

Instead of using the property, you could add another method in your interface :

public function getHandler() ;

In this method, the class will returns a $handler or create it if not already done.

Syscall
  • 19,327
  • 10
  • 37
  • 52
1

You can use abstract methods to force implementation by derived classes, instead. The $handler can be declared as a property of an abstract class so every derived class will inherit it.

abstract class Class1{
    protected $handler = "";
    abstract function toJson();
}

class Class2 extends Class1{
    public function toJson(){
        $this->handler = "a value";
        return $this->handler;
    }
}

$foo = new Class2();
echo $foo->toJson();
Caiuby Freitas
  • 279
  • 2
  • 7
  • actually I was thinking about an abstract class, but it forces to have the property but still property can be null and it will crash in run-time . – PrStandup Jan 30 '18 at 14:56