Quantcast
Channel: PHP Freaks: PHP Help
Viewing all articles
Browse latest Browse all 13200

Question about using $this inside methods

$
0
0

Hey Guys. I just wanted to know how is an attribute available when you use the pseudo variable $this
in a method, with out even initializing it in the class.

I thought that you only use $this after you initialize it in the class. Initialize meaning defining the scope, and prepending  it with a dollar sign. I.e public $var1="";

 

For example I created a method below, and have the attribute "name" available to work with just by using $this-> inside a method. I thought that $this-> is used  only to  call an existing method or attribute from within an object.

 

But in the example below I never initialized the attribute name, and I have it available to work with. Just a little confused on how that works.

class attr {
    
public function display_new(){
    $this->name;
}    
}

$new_name = new attr();
$new_name->name="John"; // Name is available and I didn't initialize it in the class "attr"
echo $new_name->name;

Viewing all articles
Browse latest Browse all 13200

Trending Articles