有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在php中引用其他对象?

我是Php新手,来自Java。我有一个Java类,如下所示:

class A {
}

class B{
}

在同一个包裹里。在类A中,我定义了一个类型为B的数据类型,如:

   B bType;

我希望在php中有同样的行为。有可能吗

有没有办法用php“打包”我的类

提前谢谢


共 (3) 个答案

  1. # 1 楼答案

    A类中定义:

    $BClass = new B(arguments for contructor);
    $BClass = new B; //without contructor
    
  2. # 2 楼答案

    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)来检测特定的数据类型

  3. # 3 楼答案

    您可以使用名称空间(即打包)。如果你真的想打包,那么你应该看看http://php.net/manual/en/book.phar.php(但我想直到现在,还没有人真的这么做)

    可以强制函数中的类型,但不能强制变量

    function (Array $bla, YourClass $test) {
       /** ... **/
    }
    

    希望有帮助