$var1 = new SampleClass();
$var2 = new SampleClass();
$var3 = new SampleClass();
$var4 = new SampleClass();
$var1 = $var1->GetRecord(1);
$var1 = $var2->GetRecord(2);
$var1 = $var3->GetRecord(3);
$var1 = $var4->GetRecord(4);
I know the latter example is more lines of code, but is either example specifically right or wrong? Is there a reason to use one rather than the other?
The second example seem to imply something happens with SampleClass when getting a record (as you’re using one instantiation for each get). I assume it’s only a bit wasteful as there is no real reason to use a separate SampleClass instantiation for each get call, but it might be confusing as is.
The former is operating on a single instance of the class, while the latter is is operating on 4 unique instances. So it depends what you are actually trying to do.
You’d be surprised how much web servers today can handle. Usually I’m way more concerned about how understandable the code is than how fast it runs. Lots of great talks on youtube on clean code and how important it is as we as devs are really spending more time reading/processing code than we spend writing code. The rather insane amount of bandwidth, cpu, memory and disk io we have available today has kinda made devs lazy. But in fairness hw/bandwidth costs are miniscule compared to dev cost, so it’s kinda to be expected.
I don’t like that approach. There is no reason “Library” should know how to instantiate Softback objects. And the way Softback actually instantiates a new object of itself is kinda confusing.
I’d much rather iterate over a data set outside the Library class in some way like this. I’d also recommend looking into using composer for auto loading classes.
class Library
{
private $books = [];
public function addBook(Book $book)
{
$this->books[] = $book;
}
}
class Softback
{
private $title = null;
private $author = null;
public function __construct($title, $author)
{
$this->title = $title;
$this->author = $author;
}
}
$library = new Library();
$books = $booksModel->getSoftbackBooks();
foreach ($books as $book) {
$library->addBook($book);
}
Note: for the code above to work you need some sort of books model that can fetch the data. Softback also need to inherit from a parent “book” class so typehinting can be used. I just assumed you’d use multiple kinds of books.
Thank you for your comments. I’m looking into Composer, and doing so re-coding using what I’ve learnt from you guys - so thank you again.!
JimL - Where you use the following:
public function addBook(Book $book)
which as far as I can see requires $book to be of type Book, if Book had extended classes such as Hardback and Softback is there a way to say it can be either hardback OR softback?
You can either do a Book Abstract class that hard and soft extend. Or you can do an Interface. An Interface would allow you to add magazines, movies, and other things that libraries have and everything that implements the interface is allowable.