Jump to content

Array slicing from a method


cintolas

Recommended Posts

Hi,Is there any way in php where I can take the result of the method and slice it directly without putting it into a variable firstFor example. I am working with Controllers in CakePHP.I make a method view($id).The following code works:

function view($id){		$mypost = $this->Post->findById($id);		$this->set('post', $mypost['Post']) ;	}

But doing this returns a parse error: Parse error: syntax error, unexpected '[

function view($id){		 		$this->set('post', ($this->Post->findById($id))['Post']) ;	}

It seems messy to create a temporary variable for something I can do inline in other languages.Is there a way to do what I am asking in php?

Link to comment
Share on other sites

try:
function view($id){		 $var=$this->Post->findById($id);		$this->set('post', $var['Post']);	}

Thanks for the reply, but my question is can I do this without having to create the $var variable?Can I do this in entirely one line of code?
Link to comment
Share on other sites

It might depend on context and the kind of objects you're working with. For example, using a DOMDocument object, this is legal:$dom->getElementsByTagName("div")->item(4)->parentNode->getAttribute("style")But none of those uses an array [index].

Link to comment
Share on other sites

The thing is, returned arrays can't be chained... it's a PHP internal problem. There have been discussions on the PHP internals mailing list about adding support for this, but it's not yet implemented. I think they'll leave it for PHP6. Placing the array in a variable and chaining from the variable on is just the workaround.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...