Asked  7 Months ago    Answers:  5   Viewed   36 times

I get a parse error when trying to use a name space inside my own function

require('/var/load.php');

function go(){

  use testClass;

    $go = 'ok';
    return $go;
}

    echo go();

 Answers

40

From Scoping rules for importing

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped

So you should put like this, use should specified at the global level

require('/var/load.php');
use testClass;

function go(){
    $go = 'ok';
    return $go;
}
echo go();

Check the example 5 in the below manual Please refer to its manual at http://php.net/manual/en/language.namespaces.importing.php

Wednesday, March 31, 2021
 
joostvandriel
answered 7 Months ago
93

You can't break/continue a loop outside a function, from within a function. However, you can break/continue your loop based on the return value of your function:

function myFunction(){   
    //Do stuff
    return $foo === 'bar';
}


foreach($x as $y) {
    if(myFunction()) {
        continue;
    }

    //Do stuff

    echo $output . '<br>';    
}
Wednesday, March 31, 2021
 
daiscog
answered 7 Months ago
94

You need to fully qualify the relative class name Yii.

The most convenient way to do this is by importing the class: just add use Yii; below your namespace declaration.

Saturday, May 29, 2021
 
Jimenemex
answered 5 Months ago
68

Second option is better if you want to implement some kind of polymorphism or to completely change function's logic. Something like this.

namespace Nkamm;

// like a PHP6
function strstr($needle, $haystack)
{
    return strstr($haystack, $needle);
}

var_dump(strstr('t', 'Long test'));

Result:

string(4) "test"

But I would not like to do such "overloads" because that will cause the mess (until they are strictly documented in project). Hence there is no sense to overwrite existing functions.

Summing up: keep your functions in your namespace, use global functions without any backslashes.

Saturday, May 29, 2021
 
jenny
answered 5 Months ago
11

Looks like a known issue in PhpStorm.

Saturday, May 29, 2021
 
Besnik
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :