Typecasting in php

I have an interface in PHP

interface IDummy{ public function DoSomething(); } 

I have another class that implements this interface.

 class Dummy implements IDummy{ public function DoSomething(){ } 

How can I type a Dummy Object IDummy object in PHP so that I can name it

 $dum = new Dummy(); $instance = (IDummy)$dum; $instance->DoSomething(); 

Can I do this in PHP?

Thanks and Regards Abishek R. Srikanant

+4
source share
3 answers

The cast is completely unnecessary. It will just work.

And Dummy objects will be considered an instance of IDummy if you ever test it using one of the hint type functions.

This works ... no casting required:

 interface I { public function foo(); }; class A implements I { public function foo() { } } function test(I $obj) { $obj->foo(); } $a = new A(); test($a); 
+4
source

If the Dummy class already implements interface IDummy , there is no need to throw $dum in IDummy - just call the DoSomething() method.

 interface IDummy { public function doSomething(); } class Dummy implements IDummy { public function doSomething() { echo 'exists!'; return; } } $dummy = new Dummy(); $dummy->doSomething(); // exists! 
+3
source

The code should be simple:

 $class = new ClassName; $class->yourMethod(); 

As noted by @konforce, type casting is not required. You might want to check out the PHP function method_exists () http://php.net/manual/en/function.method-exists.php .

0
source

All Articles