1

i have a class:

class Connect
{
    public function auth()
    {
        ... do something
    }
}

and i have a function: getfile.php

<?php
require_once($GLOBALS['path']."connect.php");
?>

the i have the: connect.php

<?php
function connect( $host, $database )
{
   database connection here
}
?>

how can i use this functions inside my class like this:

class Connect
{
    require_once("getfile.php");
    public function auth()
    {
        connect( $host, $database )
        ... do query
    }
}

is this possible?

thanks

2
  • 1
    What difficulty did you encounter when you tried? Commented Jan 20, 2012 at 18:20
  • well, im not even sure this is possibile, to require other functions inside a class, the function included is not a class, so how would i use it? Commented Jan 20, 2012 at 18:23

2 Answers 2

3

You can't add functions to a class in that manner.

If you're trying to add mixins to a class, you should read this.

Otherwise you should stick to standard OOP practices by making a base class (or abstract class) and extend it:

class Connect extends Connector
{
  ...
}

class Connector
{
  public function connect($host, $database) {
  ...
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Functions declared in the global scope is available globally. So you don't have to include it where you need it, just include the file with the function in the beginning of your script.

Secondly,

class Connect
{
    require_once("getfile.php");
    public function auth()
    {
        connect( $host, $database )
        ... do query
    }
}

this is just jibberish; you can't execute something inside the class outside of methods. If you really just want something included ONLY when that specific file is needed in that specific method, do something like this:

class Connect
{
    public function auth()
    {
        require_once("getfile.php");
        connect( $host, $database )
        ... do query
    }
}

2 Comments

u think i can add a _construct to call the require_once("getfile.php"); each time the class runs?
You could, but if the function should work globally, then you should include it in the global scope. If you only need it locally, do it in the __construct or the specified method you wan't to use it.

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.