简体   繁体   English

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

[英]How can I refer other objects in php?

I'm very new to Php and I'm from Java. 我对Php很陌生,来自Java。 I have a class in Java like this: 我有这样的Java类:

class A {
}

class B{
}

in same package. 在同一包中。 Inside class A I have defined a datatype of type B like : 在类A内部,我定义了类型B的数据类型,例如:

   B bType;

I want the same behavior in php. 我想要在php中相同的行为。 Is that possible to do so? 有可能这样做吗?

And are there any way to "package" my classes in php? 并且有什么办法可以在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). 如果您真的想打包,那么您应该看看http://php.net/manual/en/book.phar.php (但是我想直到现在,没人真正做到这一点)。

You can force types in functions but not for variables. 您可以在函数中强制类型,但不能强制变量。

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

hope it helps 希望能帮助到你

inside A class define: A类内部定义:

$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. PHP不支持静态类型,但是您可以使用类型提示在方法中定义数据类型。 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. 您也可以使用gettype($a)来检测某种数据类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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