Good day!

When using OOP in a function, I get an error, how can I use OOP functions in a normal function? I.e:

class test { public function test($text) { print $text; } } $test = new test(); function test2($text) { print $test->test($text); } 
  • um .. what is "OOP in function"? - DreamChild
  • one
    you have a clear confusion in terms - DreamChild
  • one
    In general, OOP is theoretical concepts that are practically implemented in PHP as classes and objects. Therefore, it is more correct to say "using objects or classes (static that they have) in other functions", and then people start to stupor and misunderstand what the OOP is in the function. - Alex Krass
  • In the description, the same thing occurs, well, this is so, note. - Alex Krass

3 answers 3

The test method of the test class already has a print command. Therefore, to display information, simply call $test->test($text); without print.

Or in the test method replace print $ text; on return $ text;

You can also make the test method static if it will only output the incoming information. Then the code will be like this:

 class test{ public static function test($text){ print $text; } } function text($text){ test::test($text); } 

Static (static) class methods can be called without initializing the class itself ($ test = new test).

Addition:

db.php file

 class db{ public function db($query){ query($query); } } 

function.php file

 function test($query){ $db = new db; $db->db($query); } 

index.php file

 include db.php; include function.php test($query); 

Something like this.

  • Added your answer. - terantul
  • who told you that? if the class is initialized inside the function, it is possible. - terantul

Understood.

Made test::test('Text') instead of $test->test('Text')

    Error to guess? :)
    Wanguee, that in the function you need to make another line with global $test; :)


     <?php class test { public function test($text = '') { print $text; } } $test = new test(); function test2($text) { global $test; $test->test($text); } test2('111'); ?> 

    no mistakes, everything is OK

    • No need to troll ... - Barmaley
    • will work, why not? Most sites work like this :) - thunder
    • In the answer above, the difference is written. test :: test () cannot be used for writing, for static, $ test-> test () is possible - thunder