John Davidson

php - WordPress: Error while importing Trait inside Class

0 comments
Message:


I'm using WordPress rest api, and I have created a custom theme, and I want to code using OOP. And I'm having issues importing a Trait inside a Class.


here is the code:


MyController class


<?php

namespace Controllers;

use Controllers\RespondsWithHttpStatus;

class MyController {
use RespondsWithHttpStatus;

public function __construct() {}

public function hello() {
return "hello world";
}

}

RespondsWithHttpStatus trait


<?php

namespace Controllers;

trait RespondsWithHttpStatus
{

protected function success($message, $data = [], $status = 200)
{
return array([
'success' => true,
'data' => $data,
'message' => $message,
'timestamp' => current_time( 'timestamp', 1)
], $status);
}


protected function failure($message, $status = 422)
{
return array([
'success' => false,
'message' => $message,
'timestamp' => current_time( 'timestamp', 1)
], $status);
}

}


functions.php


<?php

require_once('Controllers/MyController.php';

add_action('rest_api_init', 'greet');

function greet() {
register_rest_route('greet/v1', 'greet', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'greeting'
));
}

function greeting() {
$myController = new MyController();
return $myController->hello();
}


What is causing the problem is "use RespondsWithHttpStatus" field in MyController Class, I have tried to use namespaces and use keyword, but without luck.



My Answer:
php
namespace MyTheme;

use MyTrait;

class MyController {
use MyTrait;

public function __construct() {
// constructor code here
}

// other methods here
}


Make sure that the `MyTrait` class is defined and accessible in the same namespace or in a namespace that is imported in the file where `MyController` is defined. Also, ensure that the file containing the `MyTrait` class is included or autoloaded before the `MyController` class is instantiated.

Rate this post

4 of 5 based on 5714 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us