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
https://forums.phpfreaks.com/topic/91487-using-operator-on-new-expression-illegal/
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();
?>

Archived

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

×
×
  • 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.