user1293977
user1293977

Reputation: 149

I'm confused: What is the easiest way to define a variable for all functions in a class?

Sorry for asking something that is widely documented, but I came across so many different approaches and I'm very, very confused.

  1. public static
  2. public $foo
  3. global, which seems to be a bad way of doing it
  4. define()
  5. const constant = 'constant value';

Am I underestimating the complexity of what I'm trying to do here?

class MyClass
    {

    $foo = 'bar';

    function DoStuff()
        {
        echo $foo;
        }

    } //MyClass

Upvotes: 2

Views: 109

Answers (4)

EaterOfCode
EaterOfCode

Reputation: 2222

public $foo is a variable that everyone can access like with $my = new MyClass(); $my->foo and can set

public static $foo is a variable that everyone can access like with MyClass::foo but cant set

global $foo is a variable what everybody can set and get like $foo

define("FOO","myString") is a sort of global that but that can get by FOO but not set

const foo is like a static

Upvotes: 1

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

The static variables are available without having an instance of the class and are shared between all of the instances

The const is constant - it's value can't be changed

The public properties belong to a specific instance and can be changed by any object, not only by the instance.

All are valid ways to declare data, it depends what you need.

Do you need the data to be non-changable? (const) Do you need the data to be visible outside of the class? (public) Do you need the data to be shared between instances (static; note you can have private static as well)

Upvotes: 1

oopbase
oopbase

Reputation: 11395

If it should be only available in your class I suggest this:

class MyClass {
   private $foo = 'bar';

   public function DoStuff() {
      echo $this->foo;
   }

}

if it should be available from other classes you should implement getter and setter.

Upvotes: 4

user680786
user680786

Reputation:

Class Example
{
    private $foo = 5;

    function bar()
    {
        echo $this->foo;
    }
}

Upvotes: 5

Related Questions