クラスの簡単な説明
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 として初期化すると、関数内でのみ使用できますよね?
はい、これは関数内でのみ使用できます。関数の外でアクセスしたい場合は、スコープ定義の 1 つを使用して関数の外で定義する必要がありますpublic, protected, private。
$a_varialbe を $this->a_variable として初期化すると、2 番目のクラス内でのみ使用可能になります。正しいですか?
これは、与えるスコープによって異なりますが、とにかくクラス内でクラスを定義するべきではありません。
$a_variable を $first->second->a_variable として初期化できますか? もしそうなら、私はそれを#1、#2、#3でどのように呼びますか?
クラス内にクラスをネストしたことがないので、これには答えられません。もう一度、この構造を変更することをお勧めします。
$a_varialbe を $this->second->a_variable として初期化できますか? もしそうなら、私はそれを#1、#2、#3でどのように呼びますか?
上記の回答を参照してください:-)
クラスの入れ子
前述のように、私はこれまでに見たことがなく、それが機能することに驚いています。この構造は必ず変更する必要があります。
1 つの提案は、次のような拡張機能を使用することです。
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();