1

I am a newbie in PHP.

I have

$input = readline("\nEnter object:");

to read the name of the object that the user wants the details of, to variable $input, which by default becomes a string.

I need to check if there exists an object named $input, in any of the classes that i have defined, and call functions accordingly,like

$this->getObsDetails() if it belongs to class Obstacles,

else $this->getCharaDetails() if it belongs to class Characters.

I cannot use is_object($input) or get_class($input) function as $input is a string.

How can I efficiently achieve this?

Edit: I have a GameObjects class, which is the base class for Characters and Obstacles classes. I have a public function in GameObjects

public function printDetails() {

    /* 
    based on the class of the calling object,  which I intend to find 
    here itself using get_class($this), I intend to call respective functions as */

    $this->getCharaDetails();

    // OR

    $this->getObsDetails();    
 }

Now, outside the class using is_object($$input) I know if there exists an object named $input. But $$input->printDetails() or $input->printDetails() cannot be performed.

How do I do it?

b.g
  • 411
  • 1
  • 3
  • 19
  • I dont get the point. So, `$input` is a string right? How can you use it as an object if it's a string? – Gogol Aug 31 '16 at 06:36

2 Answers2

1

If I understand you correctly, you are trying to instantiate classes given as inputs and run specified method of the class depending on the class name.

What I would do is make a common method called run and call whatever needed, inside..

As for example:

<?php

class Cylinder{
    public function run(){
        return $this->getVolume();
    }
    protected function getVolume(){
        // your stuffs here
    }
}

class Circle(){
    public function run(){
        return $this->getArea();
    }
    protected function getArea(){
        // your stuffs here
    }
}

Then, I would check if the user inputted class exists.. and call run method if it does..

<?php

$userInput = readline("\nEnter object:");
if(class_exists($userInput)){
    $obj = new $userInput(); 
    $neededData = $obj->run();
}

Is it what you are looking for? If not, then explain your problem in a clearer fashion..

Edit: if you are using namespace, then check this thread too.

Community
  • 1
  • 1
Gogol
  • 3,033
  • 4
  • 28
  • 57
0

To check if class exists just use

http://php.net/manual/en/function.class-exists.php

To check if is object just variable variables

http://php.net/manual/en/language.variables.variable.php

is_object($$input);
nospor
  • 4,190
  • 1
  • 16
  • 25