shin
shin

Reputation: 32721

Can I use a variable without declaring by $this->myvar in php?

In the following code, variables user and permissions are not declared at the beginning like $data, $module etc. And these $this->user and $this->permissions are used in the extended class of this class.

My question is can I use variables without declaring and using $this->myvar?

Thanks in advance.

class MY_Controller extends CI_Controller {

// Deprecated: No longer used globally
protected $data;
public $module;
public $controller;
public $method;

public function MY_Controller()
{
      .......
     $this->user = $this->ion_auth->get_user();
     .........
     // List available module permissions for this user
    $this->permissions = $this->user ? 
     $this->permission_m->get_group($this->user->group_id) : array();

Upvotes: 0

Views: 194

Answers (2)

a77icu5
a77icu5

Reputation: 131

Yes !

Maybe this send a 'warning message', you can use ini_set('display_errors', 0) to avoid it.

Upvotes: -1

Phil
Phil

Reputation: 164760

Yes you can.

PHP automatically creates public properties when initially set, eg

class MyClass
{
    private $foo;

    public function __construct()
    {
        $this->bar = 'bar'; // Now contains "public $bar"
    }
}

The only time this differs is if you have a magic __set($name, $value) method which will catch an attempt to write to an undefined or non-visible (in the current scope) property.

Upvotes: 5

Related Questions