1

First of all, I want to write two class.

<?php

class A
{
    function load($v)
    {
        $this->$v = "stack";
    }
}

class Base
{
    var $lib = null;

    function __construct()
    {
        $this->lib = new A();
    }
}


$bs = new Base();
$bs->lib->load("libx");

// Current calling method
$bs->lib->libx;




// But I want this
$bs->libx;

?>

I write a MVC fremawork. CodeIgniter can do this but I could not. My english is poor. Because of this, don't talk me complicated please.

4
  • class Base should extend class A maybe ? Commented Mar 3, 2015 at 17:10
  • No I need to not use extend for this. Because there are a lot of class like this. Commented Mar 3, 2015 at 17:12
  • I think then you are better off using a shortcut method as mentioned in an answer here (which has been deleted it seems) Commented Mar 3, 2015 at 17:13
  • unfortunately i must call like this because; when I write html in View method, I can't call "$bs->lib->xx". because there is no "lib" variable in view. So I don't want to break my code and I want to do this like this. Commented Mar 3, 2015 at 17:21

1 Answer 1

1

You can add a magic __get method to Base to look for the property in lib, and return it if it exists:

class A
{
    function load($v)
    {
        $this->$v = "stack";
    }
}

class Base
{
    var $lib = null;

    function __construct()
    {
        $this->lib = new A();
    }

    public function __get($v)
    {
        if (property_exists($this->lib, $v)) {
            return $this->lib->$v;
        }
    }
}

Usage:

$bs = new Base();
$bs->lib->load("libx");

echo $bs->lib->libx, PHP_EOL;
echo $bs->libx, PHP_EOL;

Output:

stack
stack
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I wanted to this :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.