简体   繁体   中英

Simple PHP Object-Oriented $this

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.

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;    
    }
}

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.

You can declare variables in a class (aka 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 .

  • public : You can access the property anywhere
  • private : You can only access the property in the class it's declared in
  • protected : You can only access the property in the class it's declared in AND any sub-classes

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM