将一个类的公共属性应用到另一个类 [英] Applying a public property from one class to another class

查看:45
本文介绍了将一个类的公共属性应用到另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Opencart oo 编程感兴趣.

I am interested in Opencart oo programming.

在 opencart 中,从任何控制器文件中,我们可以很容易地看到这样的编程风格:-

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');
}

我可以看到,在 ControllerAccountAddress 类中,作者可以立即分配其他类生成的属性,至少不是来自扩展的 Controller 类或在同一个 php 页面中.因此,我怀疑在这种索引"方法中可以调用其他类创建的一些公共属性.

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();
?>

结果将是英语".

然后,我尝试创建另一个类:-

Then, I attempt to create another class:-

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

}
?>

那么,无论我怎么尝试,$this->lang都不能使用,我怀疑它对这个方法不可用.

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?

推荐答案

$this->lang 不能使用,因为 Person 对象没有 $lang 属性.当一个类由其他类组成时,您需要的称为组合.基本上这意味着一个对象具有持有另一个对象的属性.

$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.

希望这会有所帮助!

这篇关于将一个类的公共属性应用到另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆