rfc:instance-method-call

This is an old revision of the document!


Request for Comments: Instance and method call/property access

  • Version: 1.0
  • Date: 2010-11-26
  • Author: Felipe Pena felipe@php.net
  • Status: Under Discussion

Introduction

The purpose of RFC is to presents the support for instantiating a class and calling its methods and accessing its properties on same command. We could use one of two syntaxes below:

Syntax 1 (without brackets)

  • new foo->bar() should be read as (new foo)->bar()
  • new $foo()->bar should be read as (new $foo())->bar
  • new $bar->y()->x should be read as (new ($bar->y)())->x

Syntax 2 (with brackets)

  • (new foo)->bar()
  • (new $foo)->bar
  • (new $bar->y)->x

Examples

Using brackets

<?php
 
class foo {
	public $x = 1;
}
 
class bar {
	public $y = 'foo';
}
 
$x = 'bar';
 
$bar = new bar;
 
var_dump((new bar)->y);     // foo
var_dump((new $x)->y);      // foo
var_dump((new $bar->y)->x); // 1
 
?>

Without brackets

<?php
 
class foo {
	public $x = 1;
 
	public function getX() {
		return $this->x;
	}
	public function setX($val) {
		$this->x = $val;
		return $this;
	}
}
 
$X = new foo->setX(10)->getX();
var_dump($X); // int(10)
 
?>
<?php
 
class foo {
	public $x = 'testing';
 
	public function bar() {
		return "foo";
	}
	public function baz() {
		return new self;
	}
	static function xyz() {
	}
}
 
var_dump(new foo()->bar());               // string(3) "foo"
var_dump(new foo()->baz()->x);            // string(7) "testing"
var_dump(new foo()->baz()->baz()->bar()); // string(3) "foo"
var_dump(new foo()->xyz());               // NULL
new foo()->www();                         // Fatal error: Call to undefined method foo::www() 
 
?>
<?php
 
class foo {
	public function __construct() {
		throw new Exception('foobar');
	}
}
 
try {
	$X = new foo->Inexistent(3);
} catch (Exception $e) {
	var_dump($e->getMessage()); // foobar
}
 
?>

Patch

Changelog

  • 26/11/2010 - Posted RFC on internals
  • 27/11/2010 - New syntax proposed
rfc/instance-method-call.1290877316.txt.gz · Last modified: 2017/09/22 13:28 (external edit)