dongshanxun6479 2014-02-23 14:43
浏览 15

在实例化期间访问类函数

I've done some research and found this SO-Post and this Php Docs...

Now my problem is, it's not working!

My current php version is 5.4.12 which this feature that I'm after is compatible with 5.4. I'm wondering why it's not working?

This is what I'm after and the stuff I've tried so far...

For example, we have a class of:

class MyClass
{
    private $var = "";

    public function __construct()
    {
        // either with or without
        // return $this;
    }

    public static function newObj()
    {
        return new self;
    }

    public function setVar($var)
    {
        $this->var = $var;
    }
}

And I've tried these:

$obj = (new MyClass)->setVar("foo");

// or

$obj = MyClass::newObj()->setVar("foo");

But none work and when I get the $obj value using var_dump, it's just null.

EDIT

I've also tried and placed an echo inside the __construct to see if the class is being initialize, and it is.

  • 写回答

1条回答 默认 最新

  • duanpo2037 2014-02-23 14:55
    关注

    As setVar is not returning anything, the left hand site must be null.

    $obj = new MyClass();
    $obj->setVar("foo");
    

    will work.

    Other way, but quite unusual since setters normally do not return anything:

    ...
    public function setVar($var)
    {
        $this->var = $var;
        return $this;
    }
    ...
    
    // now this will work:
    $obj = (new MyClass)->setVar("foo");
    

    but for me this is obscure code.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度