Reputation: 149
Sorry for asking something that is widely documented, but I came across so many different approaches and I'm very, very confused.
public static
public $foo
global
, which seems to be a bad way of doing itdefine()
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
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
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
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
Reputation:
Class Example
{
private $foo = 5;
function bar()
{
echo $this->foo;
}
}
Upvotes: 5