简体   繁体   中英

How can I refer other objects in php?

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.

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

inside A class define:

$BClass = new B(arguments for contructor);
$BClass = new B; //without contructor

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM