开发者

new/method chaining in PHP

开发者_开发知识库I've written some object-orientated PHP5 code, but it won't parse and I'm not wholly sure why. I've used method chains to simplify a lot of it- and it looks like this

$head->AddTag(new Tag('meta')->Extras('http-equiv="Content-Type" content="text/html; charset=utf-8"'));

Apparently, it has unexpected T_OBJECT_OPERATOR. This seems perfectly valid to me- where's the problem?


Here:

new Tag('meta')->

sadly, chaining is not valid in conjunction with new.

Don't ask me why, I'd like to have it. (Edit: @troelskn explains why. I wasn't thinking.)

You will need to declare new Tag('meta') outside the call. Building a generic static factory class that can give you an object should also work, like so:

$head->AddTag(Factory::create("Tag", "meta")-> .....

An example should look something like this - I'm wussing out and writing a non-generic one, I'm too lazy to write a generic one right now, as that's complex :)

public static function createTag($meta)
 {
   return new Tag($meta); 
}


That's not valid syntax in PHP. The reason for that is that php both has classes and free-floating functions. Thus you could get ambiguous cases, such as:

function foo () { return "bar"; }
class foo {}
class bar {}

$x = new foo();
// Is $x a "foo" or a "bar"?

If you want chaining, you can create a function and use as a factory. Either as a static member on the class or as a free floating function. I prefer the latter, which reads as:

function foo() { return new Foo(); }
class Foo {
  funcion bar() {}
}

// Usage:
foo()->bar();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜