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

标签 php namespaces traits

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

"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() 时指定适当的命名空间。您包含该文件,但它位于另一个 namespace 中。顶部的 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"]);

贝叶斯.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";
    }
}

预测.php

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

注意 Bayes.php 中别名的使用:use a\b\Predict as P; 这是别名有助于简化代码的地方。如果未指定别名,则仅使用不带 namespace 的姓氏。

关于php - PHP 中的命名空间、特征和使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38518062/

相关文章:

PHP 函数中两个不同的结果 localhost 和 live host

php - 为一个参数发布多个值?

php - 在 laravel 5 中集成 hybrid_auth

python - 类外的变量范围

traits - 当 trait 和 type 都不在这个 crate 中时提供一个实现

php - 当在应用程序中删除所有输入值时,如何设置自动增量以在 mysql 上重置

c++ - 命名空间语法 "::Foo"

c# - 无法解析 System.Drawing.Bitmap 和 System.Drawing.ImageConverter

c++ - 查明 C++ 对象是否可调用

新类型的 Rust 特征