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

Patrioticcow
  • 26,422
  • 75
  • 217
  • 337

2 Answers2

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) {
  ...
  }
}
Community
  • 1
  • 1
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
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
    }
}
Repox
  • 15,015
  • 8
  • 54
  • 79
  • u think i can add a `_construct` to call the `require_once("getfile.php");` each time the class runs? – Patrioticcow Jan 20 '12 at 18:25
  • 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. – Repox Jan 20 '12 at 18:27