V
V
vetsinen2018-03-23 02:58:57
PHP
vetsinen, 2018-03-23 02:58:57

Is it possible to create a class object in php if the class name is given through a string?

Let's say we have a code like this:

<?php
class Audi{}
class Ford{}

function getCar($name){
    //...
}

$audi = getCar('Audi');

Is it possible to implement the getCar function without going through all the possible class names using something standard from php?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2018-03-23
@vetsinen

function getCar($className){
    return new $className();
}
demo
documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question