Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Object-Oriented PHP Basics (Retired) Inheritance, Interfaces, and Exceptions Class and Method Interaction

Why does the instructor specifically say "Don't use the $ sign for the method call? This is wrong...

At 1:10 in the video, the instructor states that the dollar sign is not required to call the method set in the $m variable. This is incorrect. The dollar sign is required, otherwise a method called "m" will try to be called & not exist, throwing a Fatal Error.

5 Answers

Exactly. I was confused when the instructor said not to use the dollar sign as this is required.

$foo = new Foo();
$funcname = "functionName";

$foo->{$funcname}(); // correct
$foo->$funcname(); // correct
$foo->funcname(); // incorrect, tries to run funcname() rather than functionName()

I'm currently going through the PHP tutorials as a refresher as there's always basic parts that are overlooked, this video is incorrect and probably should be changed. A beginner will be confused when their code doesn't work if they're running the tutorial code on their own dev environment.

Kevin Korte
Kevin Korte
28,111 Points

This is interesting.

So I found this http://php.net/manual/en/functions.variable-functions.php

If you look at the bottom of example #2, this is their example

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

I'm curious as to whether there is something we are missing, or if this was just an oversite. This is something I probably would not have caught.

Hampton Paulk

Guys

The reason my you would use the $ sign is because you are using a variable to inject a method name in place. It's kind of like when you use variables in double-quoted strings. Remember, variables are just pointers to memory locations that hold pieces of information. Although I would use $foo->{$funcname}() since this, in code, looks more proper (kind of like telling you that this is a special circumstance). In short, okay to use it in this form when referencing a variable whose name is a function name you want to use.

Cheers!

So am I correcting in thinking the video needs to be altered to correct this code error?

Igor Prymak
Igor Prymak
13,590 Points

Correct the error with the "$" sign!