0

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";
    }
}
1
  • Not sure what that Type thing should be, but $MyClass = new $CT; Commented Feb 20, 2021 at 15:07

2 Answers 2

3

You can use variables after the new keyword:

$CT = "Class1";
if (class_exists($CT))
    $MyClass = new $CT();
Sign up to request clarification or add additional context in comments.

Comments

0

You can most assuredly create a class instance by its name alone, so your code would be

<?php

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

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

$instance = new $CT();

echo $instance->Result();

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

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

See it in action here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.