1

I used to have several library classes with the exact same methods. Figured I'd learn a bit more about two important aspects of coding; Traits and DRY.

I have the following trait:

<?php

namespace App\Berry;

trait Lib
{
    public function getIDs()
    {
        $oClass = new \ReflectionClass(get_called_class());
        $aConstants = $oClass->getConstants();
        foreach($aConstants as $sKey => $mValue)
        {
            if(!is_int($mValue))
            {
                unset($aConstants[$sKey]);
            }
        }
        return array_values($aConstants);
    }
}

The following class:

namespace App\Berry;

use Lib;

class postType
{
    const POST_TYPE_BLOG_ID     =   1;
    const POST_TYPE_BLOG_LABEL  =   __('blog', 'lib');

    const POST_TYPE_PAGE_ID     =   2;
    const POST_TYPE_PAGE_LABEL  =   __('page', 'lib');

    const POST_TYPE_NEWS_ID     =   3;
    const POST_TYPE_NEWS_LABEL  =   __('news', 'lib');
}

And am calling it like this in my PicturesController class:

$cPostTypesLibrary = new postType();
$this->set('aPostTypes', $cPostTypesLibrary->getIDs());

Now to me, this seems almost exactly like the tell me to do in the docs example #4 (About using multiple traits)

The only difference I have is I have the use outside of my class due to getting cannot use class because it is not a trait

What am I missing here?

2 Answers 2

2

Your class is not using the trait, you are instead using the other use of the use keyword and trying to import the Lib class from the same namespace into, well, the same namespace.

To use traits correctly, go back to the documentation, and look at where they are placed. The use statement is placed inside of the class definition. In your case, it would look like this:

namespace App\Berry;

class postType
{
    use Lib;
    // ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

Alright so looking at the question I linked in my post I'm guessing use goes within the class definition when the class isn't in the same namespace?
No, you put it inside of the class definition when it is a trait and you want that class to use that trait. You put it outside when you want to use that class inside of yours but you don't want to type the fully qualified namespace of the class every time you want to reference it.
NP, glad to help!
2

You have to declare the trait inside the class

class postType
{
    use Lib;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.