溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

如何在thinkPHP中自定義類(lèi)

發(fā)布時(shí)間:2021-02-03 15:07:04 來(lái)源:億速云 閱讀:203 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

如何在thinkPHP中自定義類(lèi)?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。

1.通過(guò)Model調(diào)用

<?php
/**
 * 積分模型 api接口
 */
class ApiModel{
  private $url = 'http://js.yunlutong.com/Customer/Interface';
  public function test() {
    $post_data['action']    = 'sadf';
    $post_data['callback']   = '?';
    $res = request_post($this->url, $post_data);
    $firstChar = substr($res,0,1);
    if ($firstChar =='?') {
      $res = substr($res,2);
      $res = substr($res,0,strlen($res)-1);
    } elseif($firstChar == '(') {
      $res = substr($res,1);
      $res = substr($res,0,strlen($res)-1);
    }
    dump(json_decode($res,true));
  }
}

沒(méi)有繼承Model,否則會(huì)因?yàn)楸聿淮嬖诙鴪?bào)錯(cuò)。

調(diào)用,

$Api = D('Api');
$Api->test();

調(diào)用確實(shí)方便,但是總感覺(jué)有點(diǎn)不合理。這個(gè)D畢竟是操作數(shù)據(jù)庫(kù)的。

2.通過(guò)引入類(lèi)實(shí)現(xiàn),把類(lèi)放到ORG下

如何在thinkPHP中自定義類(lèi)

<?php
class Integral{
  private $url = 'http://js.yunlutong.com/Customer/Interface';
  public function test() {
    $post_data['action']    = 'sadf';
    $post_data['callback']   = '?';
    $res = request_post($this->url, $post_data);
    $firstChar = substr($res,0,1);
    if ($firstChar =='?') {
      $res = substr($res,2);
      $res = substr($res,0,strlen($res)-1);
    } elseif($firstChar == '(') {
      $res = substr($res,1);
      $res = substr($res,0,strlen($res)-1);
    }
    dump($res);
    dump(json_decode($res,true));
  }
}
?>

調(diào)用

import("@.ORG.Api.Integral");
$integralApi = new Integral();
$integralApi->test();

配置一下,自動(dòng)加載

'APP_AUTOLOAD_PATH'   => '@.ORG,@.ORG.Api',

這樣調(diào)用就方便了不管Api文件夾下有多少類(lèi),都會(huì)自動(dòng)加載,不需要單個(gè)引用import("@.ORG.Api.Integral")了。

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI