PHP OOP:方法链接
我有以下代码,
<?php
class Templater
{
static $params = array();
public static function assign($name, $value)
{
self::$params[] = array($name => $value);
}
public static function draw()
{
self::$params;
}
}
$test = Templater::assign('key', 'value');
$test = Templater::draw();
print_r($test);
如何更改此脚本以便我可以使用它?
$test = Templater::assign('key', 'value')->assign('key2', 'value2')->draw();
print_r($test);
I have the following code,
<?php
class Templater
{
static $params = array();
public static function assign($name, $value)
{
self::$params[] = array($name => $value);
}
public static function draw()
{
self::$params;
}
}
$test = Templater::assign('key', 'value');
$test = Templater::draw();
print_r($test);
How can I alter this script so I could use this?
$test = Templater::assign('key', 'value')->assign('key2', 'value2')->draw();
print_r($test);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您不能将方法链接与静态方法一起使用,因为您无法返回类级别范围(
return self
不行)。将您的方法更改为常规方法,并在您想要允许链接的每个方法中返回 $this
。请注意,您不应使用
T_PAAMAYIM_NEKUDOTAYIM
访问实例方法,因为它会引发E_STRICT
通知。使用T_OBJECT_OPERATOR
来调用实例方法。另请参阅:
You cannot use Method Chaining with static methods because you cannot return a class level scope (
return self
won't do). Change your methods to regular methods andreturn $this
in each method you want to allow chaining from.Notice that you should not use
T_PAAMAYIM_NEKUDOTAYIM
to access instance methods as it will raise anE_STRICT
Notice. UseT_OBJECT_OPERATOR
for calling instance methods.Also see:
您不应该使用静态成员:
You shouldn't be using static members:
只需使用实例变量和实例函数而不是静态变量和实例函数。
Just use instance variables and instance functions instead of static ones.
////////
类模板器
{
静态$params = array();
$
test = Templater::assign('key', 'value')->assign('key2', 'value2')->draw();
print_r($测试);
////////
class Templater
{
static $params = array();
}
$test = Templater::assign('key', 'value')->assign('key2', 'value2')->draw();
print_r($test);
通常,将静态调用和实例调用混合在一起是一种糟糕的形式,忽略该调用(除非您给出一个需要静态的理由)。您正在使用的另一个概念是调用链,它是使用返回来实现的。
Mixing a static and an instance call like that is poor form in general, omitting that one (unless you give a reason that it needs to be static). The other concept you're working with is call chaining, which is implemented using returns.