简体   繁体   中英

How to call function from another class file in php

I have a Response.php file which has a function inside and i want to call the function to another .php file.

here's the Response.php

<?php
include 'connection.php';
$response = array();
class Response_Function{
 public function fieldMissing() {
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    $response = json_encode($response);

    echo $response;
    }
}

?>

and this is the file calling the fieldMissing() function

<?php
include 'connection';
require_once 'include/Response.php';
$db = new Response_Function();
$response = $db->fieldMissing();
echo $response;
?>

就像BrianDHall说,你的工作,你需要更换echoreturn

There are two problems with your code:

1) The response array should be declared INSIDE the function (however if you need to access it from elsewhere in the class, declare it and use it as a class attribute INSIDE the class);

2) As others have pointed out, the last instruction of your function should be returning the value instead of printing it.

To summarize, your Response.php file should look like this:

<?php
include 'connection.php';
class Response_Function{
  public function fieldMissing() {
    $response = array();
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    $response = json_encode($response);

    return $response;
  }
}

You shouldn't echo in a function always use return instead and let the caller echo wherever it needs.

Response.php

    <?php

    include 'connection.php';

    class Response_Function
    {

        public $response;

        public function fieldMissing() {

            $response["success"] = 0;
            $response["message"] = "Required field(s) is missing";

            $this->response = json_encode($response);

    }
}

file calling the function fieldMissing()

   <?php

   include 'connection';
   require_once 'include/Response.php';

   $db = new Response_Function();
   $db->fieldMissing(); 

   $response = json_decode($db->response);

   echo $response->message;

  ?>

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