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) Properties and Methods Methods

josue exhume
josue exhume
20,981 Points

php methods

From the tutorial, hampton did :

    <?php
    class Product {
        public $name = 'Header Generator';
        public $price;
        public $desc;

        public function getInfo(){
            return "Product Name: ". $this->name;
        }
    }

    $p = new Product(); 

echo $p->getInfo();
    ?>

and it worked, what my question is how come the keyword "use" doesn't work and throws an error if i try to pass the $name variable this way,

        public function getInfo() use ($name){
            return "Product Name: ". $name;
        }

or how come if i make the variable $name global its definition is lost and only "Product Name" gets printed.

        public function getInfo(){
            global $name;
            return "Product Name: ". $name;
        }

1 Answer

Mike Costa
PLUS
Mike Costa
Courses Plus Student 26,361 Points
  1. I believe it is because the keyword "use" can only be used for anonymous functions. Being that getInfo() is defined within a class, its not anonymous.

  2. With your global question, its a property of the class its bound to. In order to access a property or method bound to a class, we use $this->property, or $this->method(). For learning purposes, if you want to access it globally within the class, you can change it to a public static variable and use the "self" keyword within the class, or call it outside of the class using its class name like so:

class Product{
    public static $name = 'Header Generator';

    public function getInfo(){
        return self::$name;
    }
}

$p = new Product();
echo $p->getInfo();
echo Product::$name;