PHP 中的命名空间、特征和使用

Namespace, Trait, and Use in PHP

我一直在尝试使用和理解命名空间和特征,但出现此错误:

"Trait a\b\Train not found" when I run example.php

"Trait a\b\Train not found" when I run Bayes.php

只是搞不清楚它是如何工作的以及为什么会出错。 这是我的代码: (这些文件存储在同一个文件夹中)

//example.php
use a\classification;
include_once 'Bayes.php';

$classifier = new Bayes();
$classifier -> train($samples, $labels);
$classifier -> predict([something]);

//Bayes.php
namespace a\classification;
use a\b\Predict;
use a\b\Train;
class Bayes { 
  use Train, Predict 
}

//Train.php
namespace a\b;
trait Train{
}

//Predict.php
namespace a\b;
trait Predict{
}

很抱歉我提出了愚蠢的问题,非常感谢您的帮助:

您首先需要在 Bayes.php 中包含 Train.phpPredict.php。您指的是特征,但 PHP 是如何知道这些特征的?

然后,您需要在创建 new Bayes() 时指定适当的命名空间。您包含该文件,但它位于另一个名称空间中。顶部的 use 声明作用不大。它允许您创建 new classification\Bayes() 而不是 new a\classification\Bayes().

试试这样的方法:

example.php

<?php
use a\classification\Bayes;
include_once 'Bayes.php';

$classifier = new Bayes();
$samples = "text";
$labels = "text";
$classifier -> train($samples, $labels);
$classifier -> predict(["something"]);

Bayes.php

<?php
namespace a\classification;
require_once 'Train.php';
require_once 'Predict.php';
use a\b\Predict as P;
use a\b\Train as T;
class Bayes
{ 
    use T, P;
}

Train.php

<?php
namespace a\b;
trait Train
{
    public function Train()
    {
        echo "training";
    }
}

Predict.php

<?php
namespace a\b;
trait Predict
{
    function predict()
    {
        echo "predicting";
    }
}

注意 Bayes.php 中别名的使用:use a\b\Predict as P; 这是别名有助于简化代码的地方。如果没有指定别名,它只使用没有命名空间的姓氏。

你 运行 遇到麻烦是因为你不需要你需要的文件,所以当你要求它使用一些文件时 PHP 不知道你在说什么这些 类.

example.php 需要访问 Bayes.php

use a\classification;
require_once 'Bayes.php';

Bayes.php 需要访问 Train.phpPredict.php

namespace a\classification;
require_once 'Train.php';
require_once 'Predict.php';
use a\b\Predict, a\b\Train;

class Bayes { 
  use Train, Predict 
}

注意:当需要外部资源时,请使用 require_once 而不是 include_once