2

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 the abc() method 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()?

1
  • Pass the $obj variable as a parameter to function xyz(5,$obj) .. function($j,$obj){ } Commented Sep 6, 2017 at 11:21

6 Answers 6

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

0

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

Comments

0

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

Comments

0

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;

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.