2016-08-31 3 views
0

Может кто-нибудь сказать мне, что это differnce между:В чем разница между этими переменными PHP

class Test { 
    public $var; // I know this can be accessed from outside... 

    public function __construct($var) { 
    $this->var = $var; // This 
    $this->new_var = $var; // And this ... ? this is only internal like I would write private $new_var; ? 
    } 

    public function echoVar() { 
    echo $this->new_var; 
    } 
} 

ответ

2

Фактически не будет никакого принципиального различия между этими двумя - если вы напишете необъявленное свойство в PHP (изнутри или вне класса) он будет динамически создавать новое публичное свойство. Поэтому, учитывая следующий сценарий:

<?php 
class Test { 
    public function __construct() { 
    $this->foo = 'foo'; 
    } 
} 

$test = new Test; 
echo $test->foo; 

вы получите выход foo. См. https://eval.in/632326.

Короче говоря, свойства должны быть явно указаны как private или protected, если вы хотите их скрыть.

Вы также можете реализовать магические методы __get и __set на своем классе, чтобы лучше справляться с вызовами для чтения или записи динамических свойств. Дополнительную информацию см. На странице руководства по телефону overloading.

0

Я добавлю строки комментариев к specifiy каждой переменной.

class Test { 
    public $var; // I know this can be accessed from outside... 
    //Variable/property that can be accessed from outside the class like you mentioned.  

    public function __construct($var) { 
    $this->var = $var; // This 
    //$this calls a non static method or property from a class, in this case the property `public $var`  

    $this->new_var = $var; // And this ... ? this is only internal like I would write private $new_var; ? 
    //Creates a new public property in the Test class 
    } 

    public function echoVar() { 
    echo $this->new_var; 
    //echo the property new_var from Test class. 
    } 
} 
+0

So $ this-> new_var = $ var; можно получить доступ только изнутри тестового класса, правильно? – Blue

+0

@Blue Нет, он делает общедоступную собственность, общедоступный означает, что к нему можно получить доступ извне класса. – Daan

+0

Хорошо, получилось, спасибо! - Так что с обоими я могу установить свойства для класса извне, не так ли? (public $ var и $ this-> new_var) – Blue

0

Объяснение в комментарии

class Test { 
    public $var; // This is a member variable or attribute. 
       // Something that this class has access to 
       // and any of its sub-children 

    public function __construct($var) { 
     $this->var = $var; //If you mean $this then it is 
          // the current instance of this class see below 
          //If you mean $var it is a the parameter that 
          //is passed to the method. See below as well 

     $this->new_var = $var; // update: this adds a public member to the object 
           // essentially another $var just not easily known. 
           // Not sure a good use for this except confusion and chaos. 
           // If it were just $new_var then it is a 
           // scoped variable in this method 
    } 
} 

Пример $this и parameters

$testPony = new Test("pony"); //An instance of test with a parameter of pony 
$testUnicorn = new Test("unicorn"); //An instance of test with a parameter of unicorn 

echo $testPony->var . "<br>"; 
echo $testUnicorn->var . "<br>"; 

echo $testPony->new_var . "<br>"; 
echo $testUnicorn->new_var . "<br>"; 

echo "<pre>"; 
var_dump($testPony); 

, приведенный выше вывод будет таким:

pony 
unicorn 
I like pony 
I like unicorn 
object(Test)#49 (3) { 
    ["var"]=>string(4) "pony" 
    ["new_var"]=>string(11) "I like pony" 
} 

В качестве не e конечный свалка показывает только публичные члены, если бы были частные, это было бы в формате (предположим, private $ foo) ["foo":"Test":private]=>NULL

Смежные вопросы