Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

oop

php

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
like image 665
user1293977 Avatar asked Nov 23 '25 16:11

user1293977


2 Answers

Class Example
{
    private $foo = 5;

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

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.

like image 22
oopbase Avatar answered Nov 25 '25 05:11

oopbase