Jump to content

Question about using $this inside methods


Go to solution Solved by Hall of Famer,

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;
  • Solution

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!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.