Jump to content

Question about using $this inside methods


eldan88

Recommended Posts

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;

PHP allows you to create object properties/fields on the fly. You do not have to explicitly declare a property inside your class, and it can still be created and ready to use. The visibility for these dynamically created object properties will always be public, I am not sure whether its a good practice though.

PHP allows you to create object properties/fields on the fly. You do not have to explicitly declare a property inside your class, and it can still be created and ready to use. The visibility for these dynamically created object properties will always be public, I am not sure whether its a good practice though.

got it! Thanks for the the answer!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.