OO PHP Accessing public variable from another class

前端 未结 4 1082
借酒劲吻你
借酒劲吻你 2021-02-02 14:46

I have a class like the following:

class game {

    public $db;
    public $check;
    public $lang;

    public function __construct() {

        $this->che         


        
4条回答
  •  失恋的感觉
    2021-02-02 15:33

    Since the property is public, you can access it from outside the class as $objInstance->property. It doesn't matter if you're calling it from a function, procedural script, in another object. As long as you have the instance, you can call it's public property. Ex:

    function foo($c) {
        echo $c->lang;
    }
    foo($check);
    

    Also, some advice on working with objects and such: It's considered better code if you don't create instances of objects in the other objects, but rather pass them in someway (either a setter method or through the constructor). This keeps the classes loosely coupled and results in code that is more reusable and easier to test. So:

    class Game
    {
    
    ...
    public function __construct($check, $defaultLang, $get) {
    
        $this->check = $check;
    
        $this->lang = $defaultLang;
        if (isset($get['lang']) && !$this->check->isEmpty($get['lang']))
            $this->lang = $get['lang'];
    }
    ...
    
    $game = new Game(new Check(), DEFAULT_LANG, $_GET);
    echo $game->check;
    

    The first half of this article is an accessible explanation of what is known as Dependency Injection.

提交回复
热议问题