-2

I have a test.php:

<?php

include "MyString.php";

print ",";
print strlen("Hello world!");  

and a MyString.php:

<?php

namespace MyFramework\String;

function strlen($str)
{
    return \strlen($str)*2; // return double the string length
}
print strlen("Hello world!");

The output of test.php is 24,12 but how was the output produced? What are the execution flow of test.php?

Also there is a back slash in:

namespace MyFramework\String;

function strlen($str)
{
    return \strlen($str)*2; // return double the string length
}

Is this '\' means using namespace?

lamplanp
  • 55
  • 6
  • I don't know why somebody gave this question a minus, but this is a question about PHP namespace, a new feature after PHP 5.3. If you think this question is boring or of no use, please let me know your point – lamplanp Aug 30 '14 at 12:56
  • I didn't downvote but, FYI, PHP5.3 is old news and is obsolete. – John Conde Aug 30 '14 at 12:59

1 Answers1

2

execution of test.php includes MyString.php and executes main level code in MyString.php

MyString.php prints the result of the strlen in its own namespace (ie calling MyFramework\String\strlen() rather than the standard PHP strlen() function from the global namespace) which outputs 24 (12*2).... then MyString.php terminates and control is returned to test.php

test.php next prints a comma, and then prints the result of strlen() which uses the standard PHP strlen because it's no longer executing in the MyFramework\String namespace, so the output is 12

The \ before strlen inside the namespaced strlen() function in MyString.php means use the standard (root namespace level) strlen() function

Mark Baker
  • 209,507
  • 32
  • 346
  • 385