Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialgeoffrey
28,736 PointsClass and Method Interaction
I'm finishing the introduction about POO in PHP but there is someting I don't get. When creation an object we do this:
$soda = new Product(); /* we use parenthesis in this case.*/
But in the video here, Paulk shows a little trick. He does this:
$class = "Product";
$p = new $class; /* in other words $p = new Product*/
/*But why don't we need to specify the parenthesis, why not doing this ? */
$class = "Product()";
$p = new $class;
/* I haven't tested yet, as where I'm atm, It's not possible.*/
geoffrey
28,736 Pointslol It seems you've just read my profile. I wrote this because for the most part of the world, we don't even exist :)
2 Answers
Chris Shaw
26,676 PointsHi geoffrey,
The parenthesis while they are good practise to use aren't required for classes that don't require any arguments for the constructor, so for example all 3 of the below constructors are exactly the same when the constructor runs.
<?php
$p = new Product();
$p = new Product;
$class = 'Product';
$p = new $class;
The last example you have above won't work as the parenthesis are invalid and can't be evaluated as a class name because there is no such class called Product()
which is impossible anyway.
Hope that helps.
geoffrey
28,736 PointsYes, that helped, thank you.
Jeff Busch
19,287 PointsJeff Busch
19,287 PointsHi geoffrey,
We care about all countries, large or small.
Jeff