Jump to content
Larry Ullman's Book Forums

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


KeepLearning
 Share

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.
Link to comment
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
Link to comment
Share on other sites

 Share

×
×
  • Create New...