Jump to content

Recommended Posts

If I only need to perform a single method on an object, is there anything wrong with chaining a new object?

$obj=new myObj();
$obj_prop=$obj->getProp();

$obj_prop=myStaticObj::something()->getProp();

$obj_prop=new myObj()->getProp();   //Error?

$obj_prop=(new myObj())->getProp();
Link to comment
https://forums.phpfreaks.com/topic/300965-chaining-new-objects/
Share on other sites

What's wrong with this is that it's odd (hence difficult to read) and indicates a potential problem with your class design.

 

If the instance is only (ever?) needed for a single method call, why even have an instance? Why not a static method or even a plain function?

 

As always, it's better to show concrete code instead of making up some abstract pseudo-example.

What's wrong with this is that it's odd (hence difficult to read) and indicates a potential problem with your class design.

 

If the instance is only (ever?) needed for a single method call, why even have an instance? Why not a static method or even a plain function?

 

As always, it's better to show concrete code instead of making up some abstract pseudo-example.

 

My actual code is shown below.  display() is a controller method.  myObj() and getProp() in my fictional example is myosticket() and getTopics() (I should have called it "myClass" and not "myObj" in my fictional example).  The myosticket class has multiple methods, however, for my needs in this single display() method, only one is required.  Is it better implementing it the way I show below or is it okay to change the invocation of the creation of the object defined by myosticket?

    public function display()
    {
        $osticket=new myosticket();
        $data=array(
            'data'=>empty($_POST)
            ?array('name'=>null,'email'=>null,'topicId'=>0,'subject'=>null,'message'=>null,'i_am_human'=>null)
            :$this->stripArray($_POST,array('name','email','topicId','subject','message','i_am_human')),
            'topics'=>$osticket->getTopics(['common','corporate']),
            'title'=>'Contact Us',
            'recaptcha'=>$this->getRecaptcha()
        );
        $this->displayPage($data,dirname(__DIR__).'/templates','default.html');
    }

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.