Dan Angelo Alcanar
Dan Angelo Alcanar

Reputation: 379

PHP OOP declaring properties

I have a simple inquiry, about OOP properties.

I am learning OOP. Currently, I am using CodeIgniter, and planning to move to Symfony. I want to learn OOP principles before diving in. Hope you guide me.

I just want to ask what is the difference between declaring properties like this:

FIRST:

class MyClass {
    public $name;

    public $age;

    public function someMethod()
    {

    }
}

VS

SECOND:

class MyClass {


    public function someMethod()
    {
        $name = '';
        $age = 0;
    }
}

From my understanding I will use the SECOND method if the variables/properties will be used ONLY by that method.

And the FIRST method will be used if the property/variable will be used by different methods within the class.

Hope you can enlighten me with this one. This is how I declare properties now.

Thanks, I would appreciate all your comments and shared knowledge.

Upvotes: 1

Views: 34

Answers (1)

RedElement
RedElement

Reputation: 93

You should read through the php documentation on variable scope. http://php.net/manual/en/language.variables.scope.php

Your first example would be global scope, meaning that it is accessible by any method of that class. The second example is local scope, and any variable used inside a function is by default limited to the local function scope.

Upvotes: 2

Related Questions