私はPhpを初めて使用し、Javaを使用しています。私は次のようなJavaのクラスを持っています:
class A {
}
class B{
}
同じパッケージで。クラス内で、次のようなA
タイプのデータ型を定義しました。B
B bType;
私はphpで同じ振る舞いをしたいです。それは可能ですか?
そして、私のクラスをphpで「パッケージ化」する方法はありますか?
前もって感謝します。
名前空間(パッケージ化)を使用できます。本当にパッケージ化したい場合は、 http://php.net/manual/en/book.phar.phpを参照してください(ただし、今までは誰も実際にパッケージ化していないと思います)。
関数では型を強制できますが、変数では強制できません。
function (Array $bla, YourClass $test) {
/** ... **/
}
それが役に立てば幸い
クラス内A
定義:
$BClass = new B(arguments for contructor);
$BClass = new B; //without contructor
PHPは静的型付けをサポートしていませんが、型ヒントを使用してメソッド内でデータ型を定義できます。例えば...
<?php
class A
{
public function test(B $b) // Must be a method within B or a new exception will be thrown.
{
echo 1 + $b->test(); // adds one plus the return value of $b->test() from the B class.
}
}
class B
{
public function test()
{
return 1;
}
}
class C
{
public function test()
{
$b = new B; // initializes the B class.
return $b->test(); // calls the test method within the B class.
}
}
$a = new A;
$a->test(new B); // returns 2
gettype($a)
特定のデータ型を検出するために使用することもできます。