Gerrit Luimstra
Gerrit Luimstra

Reputation: 532

Adding objects with properties and values into an array PHP

I am building a custom data handler to save some precious bandwidth for my users. Problem is, I am trying to add an object on the fly, into an array.

It is not working as expected.

Any help would be appreciated

function getName() {
   return "test";
}


class Parser {

  private $results = [];

  public function parseCalls($callArray){
    for ($i=0; $i < count($callArray); $i++) {
      switch($callArray[$i]->call){
        case 'getName':
          $results[] = (object) ['result' => getName()]; // this is where it fails.
          break;
      }
    }
  }

  public function sendResult(){
    echo json_encode($this->results);
  }

 }

$parser = new Parser();


if(isset($_POST["callArray"])){
  // $_POST['callArray'] contains [{call: 'getName'}];
  $callsArray = json_decode($_POST["callArray"]);
  $parser->parseCalls($callsArray);

}

$parser->sendResult();

How do I make it that the results array contains something like this: [{result: "test"}]

Thank you very much! :)

Upvotes: 0

Views: 352

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33813

You appear to now have solved that little conundrum but I wrote this and spotted the problem whilst doing so.

public function parseCalls( $calls=array() ){
    foreach( $calls as $i => $call ){
        try{
            switch( strtolower( $call ) ){
                case 'getname':
                    $this->results[]=(object)array( 'result'=>getName() );
                break;
            }
        }catch( Exception $e ){
            die( $e->getMessage() );
        }
    }
}

Upvotes: 1

Related Questions