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 functio开发者_运维百科n DoSomething(){
}
How can I type cast the Dummy Object to IDummy in PHP, so that I can call it as
$dum = new Dummy();
$instance = (IDummy)$dum;
$instance->DoSomething();
Can I do this in PHP?
Thanks and Regards Abishek R Srikaanth
The cast is completely unnecessary. It will simply work.
And the Dummy objects will be considered an instance of IDummy if you ever check it with one of the various type hinting functions.
This works... no casting needed:
interface I {
public function foo();
};
class A implements I {
public function foo() { }
}
function test(I $obj) {
$obj->foo();
}
$a = new A();
test($a);
If class Dummy
already implements interface IDummy
, there's no need to cast $dum
to IDummy
- just call method DoSomething()
.
interface IDummy
{
public function doSomething();
}
class Dummy implements IDummy
{
public function doSomething()
{
echo 'exists!';
return;
}
}
$dummy = new Dummy();
$dummy->doSomething(); // exists!
The code should simply be:
$class = new ClassName;
$class->yourMethod();
As @konforce pointed out, not typecasting is required. You might want to check PHP method_exists() function http://php.net/manual/en/function.method-exists.php
.
Well, it could be fun, see java functionality regarding this issue.
interface I {
public function foo();
};
class A implements I {
public function foo() { echo 'This should be accessible.'; }
public function baz() { echo 'This should not be available.'; }
}
$dum = new A();
$instance = (I) $dum;
$instance->foo(); // this should work
$instance->baz() // should not work
Note: This code throws error. It seems that you can not cast interface like that. In java is possible.
If you know the class name from the configuration or something else that you don't know, I think this should work:
$classname = 'Dummy';
$reflectionClass = new \ReflectionClass($classname);
$instance = $reflectionClass->newInstance();
// $dum = new $className; //you can do this as well I guess
if( $instance instanceof IDummy){
$instance->DoSomething();
}
精彩评论