John Davidson

php Declare a variable by type held in a string

0 comments
Message:


I am trying to declare an object by the value held in a string. So if a string holds 'Class1' i want to declare it by type Class1.


Something like this


$CT = "Class1";
if (class_exists($CT))
$MyClass = new Type($CT);

I can do something like the following, but would rather do it as above if possible.


if (isset($_GET["CT"]))
$CT = $_GET["CT"];
else
$CT = "Class1";

echo "CT = " . $CT . "<br>";

switch ($CT)
{
case "Class1":
$MyClass = new Class1;
break;

case "Class2":
$MyClass = new Class2;
break;

default:
$MyClass = new Class1;

}

echo $MyClass->Result();

class Class1
{
function Result()
{
return "I am Class 1";
}
}

class Class2
{
function Result()
{
return "I am Class 2";
}
}


My Answer:
'Class1';
$object = new $CT();

Rate this post

4 of 5 based on 9746 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us