PHP中的命名空间,特征和用法

时间:2016-07-22 04:16:48

标签: php namespaces traits

我一直在尝试使用和理解命名空间和特征但是却出现了这个错误:

  当我运行example.php

时,

“Trait a \ b \ train not found”      当我运行Bayes.php时,

“Trait a \ b \ train not found”

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

//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{
}

对不起我的愚蠢问题,真的很感谢你的帮助:“

2 个答案:

答案 0 :(得分:3)

首先,您需要在Train.php中加入Predict.phpBayes.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;这是别名可以帮助简化代码的地方。如果未指定别名,则只使用不带名称空间的姓氏。

答案 1 :(得分:1)

你遇到了麻烦,因为你不需要你需要的文件,所以当你要求它使用其中一些类时,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

相关问题