Jump to content

Store Class in Variable


TiloW

Recommended Posts

Hi guys  :)

 

I need to store different classes in various variables ..is that possible in php (5) ?

 

For example I'd like to implement a function that creates a new instances of the given class:

 

function CreateNewInstance($class)
{
  return new $class();
}

 

the function call:

 

$newObject = CreateNewInstance(TestClass);

 

Where "TestClass" is a previously defined class - but of course this doesn't work (for "TestClass" is always interpreted as a constant) ..so how to do this ???

 

I'd really appreciate any help =)

Link to comment
https://forums.phpfreaks.com/topic/164090-store-class-in-variable/
Share on other sites

I think you are talking about "Factory Pattern"

This is from PHP's help:

 

<?php
class Example
{
    // The parameterized factory method
    public static function factory($type)
    {
        if (include_once 'Drivers/' . $type . '.php') {
            $classname = 'Driver_' . $type;
            return new $classname;
        } else {
            throw new Exception ('Driver not found');
        }
    }
}
?> 

 

Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:

 

<?php
// Load a MySQL Driver
$mysql = Example::factory('MySQL');

// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?> 

nevermind ..just figured it out by myself :)

I thought it wouldn't be possible to do stuff like this:

//define class
class Car {}

//store class in variable
$variable = "Car";

//create new instance of car by using the variable
$newCar = new $variable;

 

..in fact I just forgot the quotation marks in line 5 ::)

 

thanks anyway ^^

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.