我从php.net网站上得到了代码:
<?php
class foo {
public $foo;
public $bar;
public function foo() {
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}
$foo = new foo();
echo <<<EOT
I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
EOT;
?>
但我很困惑,每个"foo"代表什么?你真的可以在不调用函数的情况下修改方法(函数)中的属性(变量)吗?
我写了一个类似的代码,但什么都没发生
<?php
class page {
public $meta;
public $buttons;
public function show_meta() {
$this->meta = "I'm a website";
$this->buttons = array(
"home" => "index.php",
"about" => "about.php"
);
}
}
$index = new page();
echo $index->meta;
echo $index->buttons["home"];
?>
我是一名php学习者,我需要您的帮助:)
function foo
是PHP4风格的构造函数(请注意,该函数与类同名)。在PHP5中,您将改为编写function __construct()
。
new foo()
实际上调用构造函数,初始化变量。
对于第一个,是的,因为您的属性是public
。
在第二种情况下,您有一个带有字符串的引用来删除警告。
$index->buttons["home"];
您永远不会调用show_meta
,因此永远不会填充数组。
这是构造函数方法的旧php语法。构造函数是特殊方法,每当创建类中的新对象时都会调用它。构造函数的新命名约定是,所有构造函数都命名为__construct
。
要使上面的代码发挥作用,必须先调用show_meta,然后再访问这两个变量或使show_meta为构造函数。
$index = new page();
$index->show_meta();
echo $index->meta;
echo $index->buttons["home"];
顺便说一句。。home是一个字符串,应该在"内,否则您至少会发出警告。