Use a trait conditionally in PHP

phptraitconditionallyuseclass

Last Update : 2023-09-22 UTC 10:38:29 AM

Answers of > Use a trait conditionally in PHP

You can outsource your conditional code (like w3coded use class debug-functions) in a trait and do something w3coded use class like that.,You can create a class with use T w3coded use class which extends the class without use T. And then w3coded use class in your code where you use the class do an if w3coded use class and instantiate the one or the other class.,As w3coded use class long as your condition can be evaluated at the w3coded use class class root, you can do the following:

You can create a class with use T which extends the class without use T. And then in your code where you use the class do an if and instantiate the one or the other class.

<?php

trait T {
}

class A {
}

class B extends A {
    use T;
}

// In an other part of code
$obj = null;

if($condition) {
    $obj = new B();
} else {
    $obj = new A();
}

/* EOF */

You can outsource your conditional code (like debug-functions) in a trait and do something like that.

//your Trait

if($isModeDbg){
    trait Dbg{
        function dbg(mssg){
            debugbarOrSomethingSimilar(mssg);
        }
    }
}else{
    trait Dbg{
        function dbg(mssg){
        }
    }
}

//your class
class Something{
  use Dbg;
}

As long as your condition can be evaluated at the class root, you can do the following:

if (<condition here>) {
    class BaseFoo
    {
        use FooTrait;
    }
} else {
    class BaseFoo {
    }
}

class Foo extends BaseFoo
{
    // common properties
}

Current topics : Use a trait conditionally in PHP

Newly Added Questions

Similar Questions

Questions :

How To Group Array Key Value

Last Update : 2023-09-22 UTC 14:04:13 PM

Questions :

PhpStorm Warning For React Attributes In Jsx File With SCSS File

Last Update : 2023-09-22 UTC 14:04:03 PM

Questions :

Why Is The File Not Showing Up In Request.files And In Request.forms Instead?

Last Update : 2023-09-22 UTC 14:03:58 PM

Questions :

Proxying Assets From React App Directory In Slim Framework?

Last Update : 2023-09-22 UTC 14:03:42 PM

Questions :

Laravel 5.4 Can't Run “php Artisan Preset React” Comand

Last Update : 2023-09-22 UTC 14:03:24 PM

Questions :

How To Update Session Values Without Signing Out?

Last Update : 2023-09-22 UTC 14:03:13 PM

Questions :

Array Is Not Visible

Last Update : 2023-09-22 UTC 14:02:53 PM

Questions :

React Routing For Login Using Symfony

Last Update : 2023-09-22 UTC 14:02:36 PM

Questions :

Sanctum With React SPA Returning 419 Page Expired

Last Update : 2023-09-22 UTC 14:02:19 PM

Questions :

How Do I Import An Input String Into Another Page

Last Update : 2023-09-22 UTC 14:02:05 PM

Top
© 2023 W3CODED - All Rights Reserved.