Object type determined at runtime

View: New views
3 Messages — Rating Filter:   Alert me  

Object type determined at runtime

by James Colannino :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hey everyone.  I have a question.  Hopefully it's clear, because I'm not
sure quite how to ask it.  Basically, I have a variety of different
objects that a variable can be instantiated as in the same block of
code, its type being determined at runtime.  I want to be able to do
something like this:

$object = new $objType();

Where $objType is the type of object, which must be determined at
runtime.  I'm sure the syntax I have above is incorrect.  My question
is, is there any way that I can determine the object's type at runtime
and do the same type of thing?

Thanks!

James

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


Re: Object type determined at runtime

by David Otton :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

2009/7/6 James Colannino <james@...>

> Hey everyone.  I have a question.  Hopefully it's clear, because I'm not
> sure quite how to ask it.  Basically, I have a variety of different
> objects that a variable can be instantiated as in the same block of
> code, its type being determined at runtime.  I want to be able to do
> something like this:
>
> $object = new $objType();
>
> Where $objType is the type of object, which must be determined at
> runtime.  I'm sure the syntax I have above is incorrect.  My question

No, you pretty much got it right:

class A{
    public function e() {
        echo "Hello World";
    }
}

$A = 'A';

$a = new $A();

$a->e();

> is, is there any way that I can determine the object's type at runtime
> and do the same type of thing?

You're asking a different thing there, but I'll throw it in for completeness:

http://uk.php.net/oop5.reflection
http://uk.php.net/manual/en/function.get-class.php

(BTW, there's a distinction between classes and objects (random link:
http://www.felgall.com/obj1.htm))

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


Re: Object type determined at runtime

by James Colannino :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Ah, thanks very much.  That was very helpful!

James



--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php