简体   繁体   中英

How to call php class function in another function

How can I call a class function in a global function with an object or included class file.

cls.php is the class file being used.

class tst { public function abc($i) { return $i*$i ; }

need to call abc function in xyzfunction in file two.php

include('cls.php');
$obj = new tst();
function xyz($j){$result = $obj->abc($j);return $result;}
echo xyz(5);

Calling $obj->abc($j) is not working. How can I call function abc() ?

Try doing it this way, first require_once the file. Then create a new instance of the class by using the $cls code then execute a function by using the final line of code.

   require_once('cls.php');
   $cls = new cls();
   $cls->function();

Make sure this is inside your function eg

public function new_function() {
       require_once('cls.php');
       $cls = new cls();
       $result = $cls->function();
       return $result;
}

Then in your function send the response of that into your current function eg

$res = $cls->new_function();
$cls->function($res);

You have to instanciate the object inside your function, not outside.

 function xyz($j){
    $obj = new tst();
    $result = $obj->abc($j);return $result;
 }

Refer the below code:

<?php

function xyz($j){   
    $obj = new tst();
    $result = $obj->abc($j);
    return $result;
}
?>

class instantiation has to be done inside the function call

If your going to use it in more function you can instantiate the class outside the function and pass as a parameter to function like this .otherwise you instantiate the class inside the function .

<?php
class tst { 

    public function abc($i) { 

        return $i*$i ; 

    }
}

$obj = new tst();

function xyz($j,$obj){

   $result = $obj->abc($j);
   return $result;

}

echo xyz(5,$obj);  
?>

Maybe you should use namespace

namespace /tst 
class tstClass { publienter code herec function abc($i) { return $i*$i ; }

and then

use tst/tstClass
$tst = new tstClass();
$result = $obj->abc($j);
return $result;

You forgot to inject in your dependency.

<?php

/**
 * @param int $j
 * @param tst $obj
 * @return int
 */
function xyz($j, tst $obj)
{
    $result = $obj->abc($j);
    return $result;
}

Don't instantiate the class inside the function, it's bad practice. Read up on dependency injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM