eldan88 Posted September 4, 2013 Share Posted September 4, 2013 Hey Guys. I just wanted to know how is an attribute available when you use the pseudo variable $thisin 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; Quote Link to comment https://forums.phpfreaks.com/topic/281861-question-about-using-this-inside-methods/ Share on other sites More sharing options...
Solution Hall of Famer Posted September 4, 2013 Solution Share Posted September 4, 2013 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. Quote Link to comment https://forums.phpfreaks.com/topic/281861-question-about-using-this-inside-methods/#findComment-1448193 Share on other sites More sharing options...
eldan88 Posted September 5, 2013 Author Share Posted September 5, 2013 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! Quote Link to comment https://forums.phpfreaks.com/topic/281861-question-about-using-this-inside-methods/#findComment-1448228 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.