2016-07-24 31 views
1

我似乎無法在另一個函數中使用它。所以我有一個名爲user_authnet($ user)的函數,我從數據庫傳遞一個數組用戶對象。在該對象內部,我存儲了authorize.net客戶配置文件ID。所以我嘗試調用Auth.net API來獲取付款方式和訂閱。AuthnetJson命名空間John Conde

如果我有

namespace JohnConde\Authnet; 

在我的腳本的頂部,然後我得到

function 'user_authnet' not found or invalid function name 

爲錯誤。我猜是因爲它不是你任何類的一部分。

如果我不把命名空間聲明,我得到

Class 'AuthnetApiFactory' not found 
即使autoload.php運行

我正在嘗試爲Wordpress製作一個插件。這裏是我的全碼:

namespace JohnConde\Authnet; 
include get_template_directory() . '/assets/vendor/authnetjson/config.inc.php'; 
include get_template_directory() . '/assets/vendor/authnetjson/src/autoload.php'; 

$request = AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY, AuthnetApiFactory::USE_DEVELOPMENT_SERVER);     

add_action('show_user_profile', 'user_authnet'); 
add_action('edit_user_profile', 'user_authnet'); 


function user_authnet($user) 
{ 
    global $request; 
    ?> 
     <h3>Stored Payment Methods</h3> 
     <input type="text" name="authnet_customerProfileId" value="<?php echo esc_attr(get_the_author_meta('authnet_customerProfileId', $user->ID)); ?>"> 
    <?php 
     if(get_the_author_meta('authnet_customerProfileId', $user->ID)) { 

      $response = $request->getCustomerProfileRequest(array(
       "customerProfileId" => get_the_author_meta('authnet_customerProfileId', $user->ID) 
      )); 

      print_r($response); 
     } 
} 


add_action('personal_options_update', 'save_authnet'); 
add_action('edit_user_profile_update', 'save_authnet'); 

function save_authnet($user_id) 
{ 
    update_user_meta($user_id, 'authnet_customerProfileId', $_POST['authnet_customerProfileId']); 
} 

回答

1

通過把該命名空間在你的頁面,你基本上是把整個頁面中該命名空間的頂部。你不想這樣做。

相反,只需將名稱空間添加到對AuthnetApiFactory::getJsonApiHandler()的調用中即可,這樣您仍然可以在全局名稱空間中工作。

// Remove the line below 
//namespace JohnConde\Authnet; 
include get_template_directory() . '/assets/vendor/authnetjson/config.inc.php'; 
include get_template_directory() . '/assets/vendor/authnetjson/src/autoload.php'; 

// Add the namespace to your call to AuthnetApiFactory::getJsonApiHandler() 
$request = \JohnConde\Authnet\AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY, \JohnConde\Authnet\AuthnetApiFactory::USE_DEVELOPMENT_SERVER);     

您還可以使用use語句來縮短這個語法位:

use JohnConde\Authnet\AuthnetApiFactory; 
include get_template_directory() . '/assets/vendor/authnetjson/config.inc.php'; 
include get_template_directory() . '/assets/vendor/authnetjson/src/autoload.php'; 

$request = \JohnConde\Authnet\AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY, AuthnetApiFactory::USE_DEVELOPMENT_SERVER);