Navneet
Navneet

Reputation: 357

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()?

Upvotes: 2

Views: 2335

Answers (6)

delboy1978uk
delboy1978uk

Reputation: 12365

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.

Upvotes: 0

GerardMA
GerardMA

Reputation: 1

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;

Upvotes: 0

Tom
Tom

Reputation: 399

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 e.g.

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 e.g.

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

Upvotes: 2

JYoThI
JYoThI

Reputation: 12085

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);  
?>

Upvotes: 0

SNG
SNG

Reputation: 357

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

Upvotes: 0

Daniel
Daniel

Reputation: 853

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

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

Upvotes: 0

Related Questions