Juliano Lima
Juliano Lima

Reputation: 721

Simplify PHP Code

I don't want to declare a variable just for something so small.. check it out

$value = $this->getValue(); 
echo $value['Setting']['value'];

/\ $this->getValue() returns a array..

There is a way to use like this: echo $this->getValue()['Setting']['value']; ? thanks

Upvotes: 0

Views: 1582

Answers (3)

Emkey
Emkey

Reputation: 5356

On your getValue(); function, make sure you return $value['Setting']['value'], so that on your calling function, you can just do echo $value;

For instance, I have this in my controller:

public function myFunction(){

     ...
     $value = $this->MyModel->getName($id);
     $this->set('value', $value);
}

...and I have this in my model to get the name value:

public function getName($id){

     $value = $this->find('first', array(
          'conditions' => array(
               'id' => $id 
          )
     ));

     return $value['MyModel']['name'];
}

...and so in your view, you can do:

echo $value;

Upvotes: 2

mark
mark

Reputation: 21743

Look at how pretty much all the classes in the cake core do it. Configure::read(), CakeSession::read(), $this->request->query(), $this->request->data() etc. They all are able to return the value via dot syntax. So you could that here, as well.

So in the end you could just say:

echo $this->getValue('Setting.value'); 

Upvotes: 0

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13263

You can do that in PHP 5.4. It is called Function Array Dereferencing. If you use <5.4 then you are out of luck.

This is not really an important problem, though. It may be slightly annoying but it is not the end of the world.

Upvotes: 4

Related Questions