Jump to content

Array slicing from a method


cintolas
 Share

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

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...