inside A
class define:
$BClass = new B(arguments for contructor);
$BClass = new B; //without contructor
Question
I'm very new to Php and I'm from Java. I have a class in Java like this:
class A {
}
class B{
}
in same package. Inside class A
I have defined a datatype of type B
like :
B bType;
I want the same behavior in php. Is that possible to do so?
And are there any way to "package" my classes in php?
Thanks in advance.
Solution
inside A
class define:
$BClass = new B(arguments for contructor);
$BClass = new B; //without contructor
OTHER TIPS
You can use namespaces (which is packaging). If you really want to package then you should take a look at http://php.net/manual/en/book.phar.php (but I guess til' now, nobody really does that).
You can force types in functions but not for variables.
function (Array $bla, YourClass $test) {
/** ... **/
}
hope it helps
PHP doesn't support static typing but you can use type hinting to define a data-type within a method. For example...
<?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
You could also use gettype($a)
to detect a certain data-type.