Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

php - Applying a public property from one class to another class

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...