PHP Namespace declaration in other file....

PHP Namespace declaration in other file....

marianidiegomarianidiego Posts: 54Questions: 17Answers: 1

My web site uses in 98% of the pages the Datatables.....

For this reason I wanted to lighten the code by putting the loading of the library in a separate file:

init.php

....
    // DataTables PHP library and database connection
    include_once( __DIR__ . "/Editor-PHP/lib/DataTables.php" );

    // Alias Editor classes so they are easy to use
    use DataTables\Editor,
        DataTables\Editor\Field,
        DataTables\Editor\Format,
        DataTables\Editor\Mjoin,
        DataTables\Editor\Options,
        DataTables\Editor\Upload,
        DataTables\Editor\Validate,
        DataTables\Editor\ValidateOptions;
....

Now my web page is shorter and more readable, but it doesn't work....

mypage.php

include_once("class/init.php");

            // Build our Editor instance and process the data coming from _POST
            Editor::inst( $db, 'examiners', 'examiners_id' )
                ->fields(
                    Field::inst( 'examiners.examiners_id' ) ->set( false ),             
                    Field::inst( 'examiners.image' )

The error generated is as follows:

<b>Error:</b> 0 - Class 'Editor' not found in file /home/sites/7a/3/30106c0d60/public_html/snr462638/admin/dist/cont/tpl_lista_examiners/examiners.php [34]<br>Error Object
(
[message:protected] => Class 'Editor' not found

How can I solve the problem?

Regards Diego

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Hi Diego,

    That's how namespaces work in PHP. Whenever you want to use the use aliased namespaces, you need to include them in that specific file.

    My understanding is that PHP doesn't allow wildcard loading of namespaces, so you can't just do use DataTables\Editor and have all its classes imported like you would in C#. It is frustrating to me too!

    Allan

  • marianidiegomarianidiego Posts: 54Questions: 17Answers: 1

    OK, thanks

  • ItracItrac Posts: 12Questions: 1Answers: 0

    Since PHP 7 you can group use declarations:

    use DataTables\Editor;
    use DataTables\Editor\{Field, Format, Mjoin, Options, Upload, Validate, ValidateOptions};
    

    This makes it a little shorter.

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    OOO! I like that. Many thanks :)

    Allan

Sign In or Register to comment.