简体   繁体   English

PHP通过类传递对象?

[英]PHP Passing an object through a class?

After restructuring my entire class layout, I'm still having trouble using multiple class instances. 重构我的整个类布局后,我仍然无法使用多个类实例。

class User {
    public $variable;
    public function getUser() {
        $this->variable = 'It works!';
        return 'bob';
    }
}

class Base {}
class One extends Base {
    public function test() {
        print_r($User->variable); // Want it to print 'It works!'
    }
}

$User = new User();
$username = $User->getUser();
if($username === 'bob') {
    $One = new One();
    $One->test(); // prints "Notice: Undefined property: One::$variable
}

What the above code does: The class User gets the username. 上面的代码做了什么:类User获取用户名。 If the username is bob , it will create an object one and try to print the variable from class User . 如果用户名是bob ,它会创建一个对象, one并尝试打印从类变量User In my real code, User is extremely intricate and passing a bunch of things with __construct just isn't what I'm looking for. 在我的真实代码中, User非常复杂,并且通过__construct传递一堆东西并不是我想要的。

I think the solution ( which is why I titled this question as so ) would be to create a new class User within class Base but I just can't wrap my head around having to create a whole new object and re-initiate everything just to get the username. 我认为解决方案( 这就是为什么我这样称呼这个问题 )将是在类Base创建一个新类User但我无法完全创建一个全新的对象并重新启动所有内容获取用户名。

Inject your User instance: 注入您的User实例:

class One {
    private $user;
    public function __construct(User $user) {
        $this->user = $user;
    }
    public function test() {
        print_r($this->user->variable);
    }
}

$User = new User();
$One = new One($user);
$One->test();

This doesn't have any undue effects with regards to efficiency, as the instance is passed by reference as opposed to copied. 这对效率没有任何不适当的影响,因为实例是通过引用传递而不是复制。

The class One does not know about the $User variable and therefore can not access it. One不知道$User变量,因此无法访问它。

You could either pass the variable to the class in the constructor or set it after creation of an object of the class. 您可以将变量传递给构造函数中的类,也可以在创建类的对象后设置它。

class One extends Base {
    protected $user;
    public function setUser(User $user) {
        $this->user = $user;
    }
    public function One(User $user) {
        $this->setUser($user);
    }
    public function test() {
        print_r($this->user->variable);
    }
}

Or (but please don't, it is bad practice) set the $User variable to global. 或者(但请不要,这是不好的做法)将$User变量设置为global。

global $User

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

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