简体   繁体   中英

How to create a function that makes instances of multiple different abstract classes in PHP?

I am trying to build the following code, but i cannot understand how to define the instance variable, because it is an object

function getInstance($productName)
{   

    switch ($Name) {
        case Name1:
            $instance = new Class1();
            break;
        case Name2:
            $instance = new Class2();
            break;
        case Name3:
            $instance = new Class3();
            break;

        default:
            break;
    }

    return $instance;
}

Just define it as null . Also you can throw an exception in situation when $productName is not in the list.

Example:

<?php

class Class1 {}
class Class2 {}
class Class3 {}

function getInstance($productName)
{
    $instance = null;
    switch ($productName) {
        case "Name1":
            $instance = new Class1();
            break;
        case "Name2":
            $instance = new Class2();
            break;
        case "Name3":
            $instance = new Class3();
            break;

        default:
            throw new \Exception("Unknown type ($productName)!");
            break;
    }

    return $instance;
}

echo get_class(getInstance("Name1"));

I think this may help you .. though I am not clear about your making instance, but you can define it as null.

function getInstance($productName)
{   
    $instance = null;

    switch ($productName) { // $Name should be productName
        case Name1:
            $instance = new Class1();
            break;
        case Name2:
            $instance = new Class2();
            break;
        case Name3:
            $instance = new Class3();
            break;

        default:
            break;
    }

    return $instance;
}
  1. Read how to use Reflection
  2. Read how it works in PHP http://php.net/manual/en/class.reflectionclass.php

It will solve your problem.

<?php 
function getInstance($productName){
    $productToClass=["product1"=>"class1","product2"=>"class2","product3"=>"class3"];
    return new ReflectionClass('Object\'.$productToClass[$productName]); 
}

?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM