user332070
user332070

Reputation: 31

New dynamic instance in php of a class at runtime

I have different classes in which I have different properties. Now I want to instantiate these classes at runtime. Please have a look on my Example. Thank you for your help.

   class costumers
{
     $ Name;
...
}

class users
{
   $ Username;
...
}


class db_helper{
...
public function select (object $table, $columns, $limit, $offset) {
     // Instance the object like
      $out = new typeof ($table);
}

}

Upvotes: 0

Views: 1040

Answers (3)

michail_w
michail_w

Reputation: 4471

$className = get_class($table);
$out = new $className();

If you want to do something more, please read about reflection.

Upvotes: 0

martin
martin

Reputation: 96889

I think what you're trying to do is to create a new instance of the same class as the $table object? Then it's simple with get_class() function:

class db_helper{
    ...
    public function select (object $table, $columns, $limit, $offset) {
        // Instance the object like
        $class = get_class($table);
        $anotherTable = new $class();
        // ...
    }
}

Upvotes: 1

Poiz
Poiz

Reputation: 7617

Perhaps you may want to take a look at this commented Code. It may give you some hints....

<?php

    class costumers {
        protected $Name;
        //...
    }

    class users {
        protected $Username;
        //...
    }


    class db_helper {
        //...
        // NOTICE THAT THERE IS NO TYPE-HINT HERE...
        // BAD PRACTICE! BUT THIS IS TO DEMONSTRATE 
        // THE POSSIBILITIES AVAILABLE TO YOU IN THIS CASE...
        public function select($table, $columns, $limit, $offset) {
            // INITIALIZE $out TO NULL TILL YOU KNOW MORE...
            $out    = null;
            if(is_object($table)){
                // IF $table IS AN OBJECT....
                // JUST START USING IT WITHOUT INSTANTIATION:
                $out = $table;
            }else{
                if(class_exists($table)){
                    // Instance the object like
                    $out = new $table;

                }
            }
        }
        // START USING THE OBJECT: $out
    }

Upvotes: 0

Related Questions