8flriq
Last Updated: February 25, 2016
·
2.38K
· rougin
Profile

Add user-defined functions inside a method of a class in PHP

I've recently found out that you can add user-defined functions inside a method of a class in PHP. Just look at the sample below:

class Sample
{
      public function __construct()
      {
           function add_function_here()
           {
                  return 'hello world!';
           }
      }
}

Then let's declare the class:

$sample = new Sample();

And then you can now call the function.

echo add_function_here();

You can also use the defined function in other methods in the same class. I'm not sure if it is also possible to call it on other classes.

NOTE: This will only work in the __construct() magic method. Thanks to christophererk for correcting my mistake. :D

Say Thanks
Respond

4 Responses
Add your response

13219
0 ican oqyuoswt09md1pi e9gmv75tybmwvli wv3l0uvs4kjba3zdd3f8nfsauqvoq1euaf1prgx

This is wrong.

You would need to do something more like this: http://pastebin.com/scbRGSva

What you have would result in an error because the function is undefined. You still need to reference the class when calling the function.

over 1 year ago ·
13251
Profile

Oh I see. This will only work if the function is defined in the __construct() magic method. I'm sorry if this information is misleading. :D

over 1 year ago ·
15330
Jeromesw

Please don't.

This makes absolutely no sense. Although it seems to be possible to do it like this, why would you define a global function in a class constructor and what would be the advantage over defining it globally in the first place?

The code @christopherk provided is standard PHP OOP and correct. What you propose has the same limitations as normal functions in the global space. So, if you would declare a second class with the same method in the constructor, you would get a fatal error:

<?php
# test.php
class Sample
{
      public function __construct()
      {
           function add_function_here()
           {
                  return 'hello sample1!';
           }
      }
}

class Sample2
{
      public function __construct()
      {
           function add_function_here()
           {
                  return 'hello sample2!';
           }
      }
}

$sample = new Sample();
$sample2 = new Sample2();
$ php -f test.php

Fatal error: Cannot redeclare add_function_here() (previously declared in test.php:7) in test.php on line 18
over 1 year ago ·
15334
C622e9dd7cb339a605f70b219469d3c8

Why wouldn't you use a public method on Sample? Surely if the function you're defining in the constructor contains logic that needs to be accessible outside of the class then a public method is the obvious solution. If you're trying to encapsulate logic into a function that should only be used by this class then why not a protected or private method? That won't be inadvertently shoved into the global scope?

over 1 year ago ·