Jump to content

Ways of calling a class's method inside another class


play_

Recommended Posts

Ok. I know you can pass the object of a class as an argument. Example:

 

class A {
    function test() {
        echo "This is TEST from class A";
    }
}


class B {
    function __construct( $obj ) {
        $this->a = $obj;
    }

    function test() {
       $this->a->test();
    }

}

 

Then you could do:

 

$a = new A();

$b = new B($a);

 

 

Ok so that's one way i know of.

 

I also thought that you could make a method static, and do this: (assuming class A's test is 'static')

class B {
    function test() {
       A::test(); 
   }
}

 

But that is not working.

 

 

I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks :)

  • 3 months later...

hi

 

And what if i want to use a Class inside a Class?

example:

class vbtwitter{
    
    /**
     * Twitter object
     *
     * @var twitter object
     */
    private $twitterconnection;
    
    function __construct()
    {

    }
    
    function init()
    {
        global $vbulletin;
        $this->twitterconnection = new Twitter($vbulletin->userinfo['twitter_username'], $vbulletin->userinfo['twitter_password'], 'vbtwitter');
    }
    
    public function sendthread(&$threadid)
    {
        // here now call some methods from $this->twitterconnection
// this->twitterconnection->methode....
    } 

  • 2 years later...

Class inside a class is fine.

 

There's also inheritance.

 

All of which are fine ways to have objects interact with each other.

 

Your issue should work fine.

<?php 

class a {
public static function func() {
	return 'foobar';
}
}
class b {
public function method() {
	return a::func();
}
}

$obj = new b;
echo $obj->method();

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.