0

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);
}

}

3
  • could you be a little more descriptive? what is new typeof()? Which of the 2 classes (costumers and users) are you intent of instantiating within the select function? And, where is this select function declared? Commented Sep 24, 2016 at 8:45
  • I want to genarte a new instance of the table object. Commented Sep 24, 2016 at 8:57
  • Then you are going about it the wrong way.... because as you can see form your own code, $table is already an Object.... not a Classand therefore you can directly start using $tablewithout instantiating it again..... Commented Sep 24, 2016 at 9:06

3 Answers 3

1

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();
        // ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
    }

Comments

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

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

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.