Reputation: 1394
I'm trying to brush up on some object oriented basics. I wrote this simple script but am confused as to why it works the way it does.
class Foo
{
function run($text = null)
{
$this->bar = strtolower($text);
echo $this->bar;
}
}
$foo = new Foo;
$foo->run('THIS IS SOME TEXT IN LOWER CASE');
The script outputs "this is some text in lower case" as expected.
But what i'm confused about is why I can do this without actually declaring the $bar
variable. Why can I just use $this->bar
? Maybe i'm not understanding how $this
works properly, but I always thought you had to declare a variable prior to using it in the class. For example public $bar;
Thanks for any insights you may have.
Upvotes: 1
Views: 151
Reputation: 10617
You would need to put protected
, or private
in front of your variable outside of your class methods to declare a class variable as anything but public
. In PHP assignment is declaration, if it's not already declared. Note, you can also do this:
$ary = array('a', 'b', 'c', 'd');
foreach($ary as $v){
$newArray[] = $v;
}
Notice, I never declared $newArray = array();
before the loop.
Upvotes: 0
Reputation: 133
You should take a look at http://php.net/manual/en/language.oop5.magic.php
Consider that the same way you declare a variable that did not exist before, out of an object, the same way will happen inside objects, cause they are poorly typed.
Upvotes: 0
Reputation: 9444
You can declare variables in a class (a.k.a. properties) like so:
class Foo {
public $bar;
}
Note the public
keyword. Here, we are declaring the property's visibility. There are three types of visibility: public
, private
, and protected
.
This also applies to methods. I won't go into too much detail, but you can read more here.
If you don't declare a property, but set one in a method like you did in your example, PHP will automatically declare it for you and assign the value you specified.
Upvotes: 0
Reputation: 158150
PHP will auto-declare object variables as public if you are accessing them without declaring them as class members before. This is no magic, just a "feature" ;)
However, a good design should not use this "feature" but declare any class members explicitly. Your class should look like this:
class Foo
{
/**
* some description
*
* @var <type>
*/
protected $bar;
...
function run($text = null)
{
$this->bar = strtolower($text);
echo $this->bar;
}
}
Upvotes: 3