首先,正如 Jared Farrish 已经说过的那样,这不是有效的 PHP。它public $myvar
而不是public myvar
. 变量名总是以 .开头$
。
在类中声明变量时:
<?php
class A
{
private $var;
}
如果通过访问该变量将在所有方法中自动可用$this
(除非方法是静态的,但这是另一回事)。所以这会起作用:
<?php
class A
{
private $var;
public function foo () {
// This works
$this->var = 1;
// This is a completely different thing and does not change
// the contents of A::$var
$var = 1;
}
}
现在global
完全不同了。在 PHP 中,你不能这样做:
<?php
$global_a = 123;
function myfunc ()
{
// You wont actually change the value of $global_a with this
$global_a = 1234;
}
echo $global_a; // still 123
你会认为这会起作用,但全局变量不会自动用于函数。这就是global
进来的地方:
<?php
$global_a = 123;
function myfunc ()
{
global $global_a;
$global_a = 1234;
}
echo $global_a; // now it will be 1234
我建议您阅读 PHP 中的变量范围,然后您可以继续阅读 PHP中的 OOP。
PHP 是一种非常古怪的语言。仅仅因为某些东西在大多数语言中以某种方式工作并不意味着它可以在 PHP 中工作。大多数时候,它不会。因此,最好尽可能多地教育自己。
希望这可以帮助