简体   繁体   English

如何在另一个函数中调用php类函数

[英]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. cls.php是正在使用的类文件。

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

need to call abc function in xyzfunction in file two.php 需要在文件two.php中的xyzfunction中调用abc函数

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. 调用$obj->abc($j)不起作用。 How can I call function abc() ? 如何调用函数abc()

Try doing it this way, first require_once the file. 尝试以这种方式进行操作,首先require_once文件。 Then create a new instance of the class by using the $cls code then execute a function by using the final line of code. 然后使用$cls代码创建该类的新实例,然后使用最后一行代码执行一个函数。

   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. 阅读有关依赖项注入的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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