# Object instantiation

- Thread: https://externals.io/message/37136
- Original archive: https://news-web.php.net/php.internals/37136
- Started by Sam Barrow on 2008-04-18T16:23:22+00:00
- Messages: 3
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #37136 — Sam Barrow — 2008-04-18T16:23:22+00:00

URL: https://externals.io/message/37136#37136

I had a question about object instantiation.

You can do this:

function createObject() {
	return new myObject;
}
$result = createObject() -> myMethod();

But you can't do this:

$result = new myObject -> myMethod();

Is there a technical reaosn as to why this can't be done? If not can
this be changed?

---

## #37139 — Stanislav Malyshev — 2008-04-18T18:42:28+00:00

URL: https://externals.io/message/37136#37139 · In reply to: #37136

Hi!

> $result = new myObject -> myMethod();
> 
> Is there a technical reason as to why this can't be done? If not can
> this be changed?

I think this can not be parsed unambiguously. This could be new 
(expression with ->) or (new expression)->expression. E.g., what this means:

$a = new $foo->bar();

is it a new object whose name given by $foo and then bar() called on it, 
or is it a new object whose name given by variable $foo->bar with empty 
ctor?

Also, I'm not sure it's a good style - if you are creating object just 
to drop it immediately in the same expression, maybe it should be static 
method that creates the object internally?
-- 
Stanislav Malyshev, Zend Software Architect
stas@zend.com   http://www.zend.com/
(408)253-8829   MSN: stas@zend.com

---

## #37140 — Sam Barrow — 2008-04-18T18:46:58+00:00

URL: https://externals.io/message/37136#37140 · In reply to: #37139

> Hi!
> 
> > […]
> 
> I think this can not be parsed unambiguously. This could be new 
> (expression with ->) or (new expression)->expression. E.g., what this means:
> 
> $a = new $foo->bar();
> 
> is it a new object whose name given by $foo and then bar() called on it, 
> or is it a new object whose name given by variable $foo->bar with empty 
> ctor?

Yeah, that makes sense.

> Also, I'm not sure it's a good style - if you are creating object just 
> to drop it immediately in the same expression, maybe it should be static 
> method that creates the object internally?
