Jump to content
Larry Ullman's Book Forums
KeepLearning

Why Is A Static Class Instance Better? (Page 150 Of The Yiibook2)

Recommended Posts

Larry, on page 150 of the YiiBook2 (latest version), you write that the following code is "verbose, redundant, and illogical":

 



$model = new Page();
$model = $model->findOne($id);


 

Instead of creating an instance of the Page class, as shown above, you say we should use a static class instance (or static method?), like this:

 



if (($model = Page::findOne($id)) !== null) {
return $model;


etc.

 

I don't understand why the first example is "verbose, redundant, and illogical", and why the second example is preferred. Can you please explain this?

 

Thanks.

Share this post


Link to post
Share on other sites

Well, to be fair, my language is a bit much, but in the old way (and the above example), a Page instance is created whether or not the $id is valid. In the new way, a Page instance is only created if the $id is valid. In other words, the old way says "let's make one of these and then see if we should have one of these" whereas the new way says "let's see if we should have one of these".

  • Upvote 1

Share this post


Link to post
Share on other sites

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.   Paste as plain text instead

  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.

Loading...

×
×
  • Create New...