4

I have a class with own methods and on the other side a php file what contains external methods. From documentation is clear that inside of a class includeing external functions is not possible

How could I inculde this functions in my class. Making an another class and extend my first class it can not be an option.

7
  • In the file you want to include... are these actual methods on a class or are these free floating functions? Commented Nov 6, 2012 at 20:18
  • they are free floating functions Commented Nov 6, 2012 at 20:21
  • 2
    Don't. The point of a class is to encapsulate functionality and stop you from spreading related code across multiple files. Commented Nov 6, 2012 at 20:24
  • Yeah I tought so but I did not want to refactor all codes what I got Commented Nov 6, 2012 at 20:26
  • 2
    This seems like a valid scenario. You are consuming third party code and you don't want to touch it - simply wrap the parts you need in an adapter class so the rest of your application doesn't have to know about it. Commented Nov 6, 2012 at 20:42

2 Answers 2

6

You can't. All class definition, including methods and fields must be on the same file. You can't declare the same class in two different files.

Extending, or using traits (if you have PHP 5.4.x+), are your only options.

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

Comments

5

You can call external functions from a class, even if they are not enclosed in a class of their own:

Global.php

<?php
function doSomething() {
    return 'Hello';
}
?>

ExampleClass.php

<?php
include_once('Global.php');

class ExampleClass
{
    public function example() {
        return doSomething();
    }
}
?>

Although you probably wouldn't have the include in the actual class file.

2 Comments

That looks much too magical to me. But it kinda beats the point, as you would still have to declare wrappers for each function (or worse, use __call()).
It is not magical, it is called delegation. It isn't clear from the question whether the OP intends to simply call an external function to perform some task or wrap every function to disguise it as part of the class - I think you are assuming the latter, which could well be true - but you don't need to use __call() and there is no magic - it is just calling a function.

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.