Jump to content

Using -> operator on 'new' expression - Illegal?


deadimp

Recommended Posts

Is using the -> operator on an expression (not a variable) always illegal? Or am I doing something wrong?

Ex.

class Test {
var $var, $extra;
function __construct($var) {
  $this->var=$var;
}
//Allow variables to be set right off of a class, returning this for chaining - like jQuery or whatever else there is
function extend($extra) {
  $this->extra=$extra;
  return $this;
}
}
$bleat=(new Test("biscuit"))->extend("super-something");

Throws: "syntax error, unexpected T_OBJECT_OPERATOR"

I know you can do this in C++ and Java, due to their 'type parametric' nature, and I assumed it would work with PHP.

Info: PHP 5.2.5, XAMPP, WinXP

 

I guess I'm gradually growing more disappointed in some of PHP's non-flexible syntax. I'm not sure whether it's just a design flaw, or a design scheme meant to force 'cleaner' code.

 

EDIT: One ugly workaround:

function& w(&$x) { return $x; }
$bleat=w(new Test("biscuit"))->extend("super-something");

 

NOTE: There's no point to this impelmentation. It's meant for demonstrating.

Link to comment
Share on other sites

If you wish to do that then you'll have to create a method which gets a new instance.

 

<?php
class Test
{
public function __construct($argA)
{
	// do stuff
}

public static function getNewInstance($argA)
{
	return new self($argA);
}

public function someSortOfFunction()
{
	echo 'Called ' . __METHOD__;

	return $this;
}
}

$obj = Test::getNewInstance('testing')->someSortOfFunction();
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.