Using static method that include once and initialize an object in Yii2

539 views Asked by At

I have created the following tools class in vendors of Yii2 application:

//@vendor/saidbakr/tools/FoxText.php
namespace FoxTools;
class FoxText
{
  public static function normalise($txt)
  {
    include(dirname(dirname(__DIR__))."/I18N/Arabic.php");  

     $norm2 = new \I18N_Arabic('Normalise');        

     return $norm2->stripTashkeel($txt);

  }
}

When using FoxText::normalise() inside a loop or reusing it inside any other block of the code, I have got the following Error:

PHP Compile Error – yii\base\ErrorException

Cannot redeclare class I18N_Arabic_Normalise 1. in C:\xampp-2\htdocs\feqh-site\vendor\I18N\Arabic\Normalise.php

I tried to use include_once and define the method without static and initializing as dynamic variable

$p = new FoxTools\FoxText() then $p->normalise() but it failed too. I also tried to:

use FoxTools\FoxText;
use FoxTools\FoxText as text2;
use FoxTools\FoxText as text3;

and it succeeded but it is not useful in loop.

What I would like to mention again, ** it works fine if I used it once**

1

There are 1 answers

3
topher On

Use namespaces instead of include or require. This is the recommended Yii2 method for importing files. Assuming Arabic.php is in the \I18N namespace:

namespace FoxTools;
use \I18N\Arabic;
class FoxText
{
...

Alternatively, you can use require_once instead of include:

require_once(dirname(dirname(__DIR__))."/I18N/Arabic.php");