类的简要说明
class foo{
// This can be accessed anywhere
public $i_am_public;
// This can be accessed within this class and any sub classes
protected $i_am_protected;
// Thi can only be accessed within this class
private $i_am_private;
// This function can be accessed anywhere
public function foo_function(){
// This variable is only available in this function
// it cannot be accessed anywhere else
$variable = 'Hello World';
// However, you can access any of the other variables listed above
// like so
$this->i_am_public = 'public';
$this->i_am_protected = 'protected';
$this->i_am_private = 'private';
// Write these variables
echo $this->i_am_public;
echo $this->i_am_protected;
echo $this->i_am_private;
}
}
$foo = new foo;
$foo->foo_function();
// You can change any publicly defined variables outside
// of the class instance like so
$foo->i_am_public = 'testing';
问题的具体答案
在我继续之前,我强烈建议您不要在类中定义类!相反,使用我将在稍后解释的类扩展。事实上,我很惊讶你的代码甚至可以工作!
如果我将 $a_variable 初始化为 $a_variable 它仅在函数内部可用,对吗?
是的,这仅在函数内部可用。如果要在函数外部访问它,则需要使用范围定义之一在函数外部定义它public, protected, private
。
如果我将 $a_varialbe 初始化为 $this->a_variable 它只能在第二类中使用,对吗?
这取决于你给它的范围,但无论如何你都不应该在一个类中定义一个类。
我可以将 $a_variable 初始化为 $first->second->a_variable 吗?如果是这样,我将如何在#1、#2 和#3 中调用它?
我无法回答这个问题,因为我从来没有在一个类中嵌套过一个类,我再次敦促你改变这个结构。
我可以将 $a_varialbe 初始化为 $this->second->a_variable 吗?如果是这样,我将如何在#1、#2 和#3 中调用它?
请参阅上面的答案:-)
嵌套类
如前所述,我以前从未见过这个,我很惊讶它甚至可以工作。你绝对应该改变这个结构。
一个建议是使用这样的扩展:
class foo{
// This can be accessed anywhere
public $i_am_public;
// This can be accessed within this class and any sub classes
protected $i_am_protected;
// Thi can only be accessed within this class
private $i_am_private;
public function foo_function(){
echo 'Hello World';
}
}
class bar extends foo {
// This is a public function
public function baz(){
// These will work
$this->i_am_public = 'public';
$this->i_am_protected = 'protected';
// This will not work as it is only available to
// the parent class
$this->i_am_private = 'private';
}
}
// This will create a new instance of bar which is an
// extension of foo. All public variables and functions
// in both classes will work
$bar = new bar;
// This will work because it is public and it is inherited
// from the parent class
$bar->foo_function();
// This will work because it is public
$bar->baz();