douqiao1887 2013-04-09 11:52
浏览 14
已采纳

将公共属性从一个类应用于另一个类

I am interested in Opencart oo programming.

In opencart, from any controller file, we can easily see programming style like this:-

class ControllerAccountAddress extends Controller {
    private $error = array();
    public function index() {
            if (!$this->customer->isLogged()) {
                $this->session->data['redirect'] = $this->url->link('account/address', '', 'SSL');
}

I can see, inside the ControllerAccountAddress class, author can immediately assign properties generated by other class, which at least is not from the extended Controller class or within the same php page. Therefore, I suspect that, some public properties created by other classes were available to be called for usage in this method of "index".

However, when I tried another class like this:-

<?php
class Language{
    public $lang;

    function __construct($the_lang) {
        $this->lang = $the_lang;
    }

    function get_lang(){
        echo $this->lang;   
    }
}
?>

<?php
$try = new Language('English');
$try->get_lang();
?>

Result would be "English".

Then, I attempt to create another class:-

<?php 
class Person {
    public $name;
    function trial() {
        $something = $this->lang . "OK";
    }

}
?>

Then, no matter how I try, the $this->lang cannot be used, and I suspect it has not available to this method.

What can I do so that I can generate properties that are available to be used in other class methods?

  • 写回答

2条回答 默认 最新

  • dongqianzong4275 2013-04-09 12:01
    关注

    $this->lang cannot be used since Person object dosen't have $lang property. What you need is called composition, when one class is composed of other classes. Basicly this means that one object has property that holds another object.

    So you want Composition, and you need Dependency Injection to enable this.

    For Person to use Language you need this:

    class Person {
         public $name;
         public $lang; // This is object!
    
         public function __construct($lang) {
             $this->lang = $lang;
         }
    }
    
    $lang = new Language();
    $john = new Person($lang);
    

    Now you can access language like this:

    $jonh->lang->method();
    

    This example shows you how to push object through object constructor using Dependency Injection. Just read more about Composition and Dependency Injection.

    Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法