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 trial

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,362 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;