Jump to content

[SOLVED] Refer to another class


Jonob

Recommended Posts

New to php, but learning as I go.

 

Lets say I have a php file called user.php

class user
{
   function first();
   {
      Some code here
      return $result;
   }

   function second();
   {
      //I want to refer to function first
      $test = $this -> first()
      return $test
   }
}

 

OK cool, so if I want to refer to another function in the same class, then I use $this ->

 

Now, what happens if I have a second php file called (for example) company.php, and inside that file I have a class called company, and inside that class a function called get_company(). I want to use get_company() in user.php, so at the top of user.php I put

 

require_once("company.php")

 

Lets say I want to use the get_company function in the second() function. I've tried to reference it as

 $test = $this -> get_company()

but it throws an error.

 

I guess my question is: how do I reference a function in a different class?

 

Link to comment
Share on other sites

<?php

class a {
  function boo() {
    echo "hello from a";
  }
}

class b {
  private a;
  function __construct() {
    $this->a = new a;
  }
  function boo() {
    $this->a->boo();
    echo "hello from b";
  }
}

$b = new b;
$b->boo();

?>

Link to comment
Share on other sites

Thanks guys, works perfectly  ;D

 

On the same topic, assuming the following:

-I have one class in a php file

-I have many functions in that class

-I need to reference other classes from other php files in only ONE of those functions

 

Is it considered OK coding practise to put the

require_once("filename.php") 

code inside that single function? Or should it be just after the opening

<?php

tag?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.