I'm trying to understand namespaces and include in PHP, and came up with an example that looks like this:
$ tree test/class/
test/class/
├── Bar.php
└── testin.php
Here are the bash commands I'm running to set up the example:
mkdir -p test/class
cat > test/class/Bar.php <<EOF
<?php
namespace Foo;
class Bar {
  function __construct() { // php 5 constructor
    print "In Bar constructor\n";
  }
  public function Bar() { // php 3,4 constructor
    echo "IT IS Bar\n";
  }
}
?>
EOF
cat > test/class/testin.php <<EOF
<?php
use Foo;
require_once (__DIR__ . '/Bar.php');
$bar = new Bar();
?>
EOF
pushd test/class
php testin.php
popd
And when I run this I get:
+ php testin.php
PHP Warning:  The use statement with non-compound name 'Foo' has no effect in /tmp/test/class/testin.php on line 2
PHP Parse error:  syntax error, unexpected '=' in /tmp/test/class/testin.php on line 4
Ok, so how could I modify this example, so it testin.php reads the class in Bar.php and instantiates an object out of it, while using use and namespaces?
EDIT: The second file setup should have the "EOF" quoted, because of presence of dollar sign $:
cat > test/class/testin.php <<"EOF"
<?php
use Foo;
require_once (__DIR__ . '/Bar.php');
$bar = new Bar();
?>
EOF
... then running the php scripts gives the error:
+ php testin.php
PHP Warning:  The use statement with non-compound name 'Foo' has no effect in /tmp/test/class/testin.php on line 2
PHP Fatal error:  Class 'Bar' not found in /tmp/test/class/testin.php on line 4
EDIT2: If I declare the full path, beginning with \ which signifies the root namespace, then it works:
cat > test/class/testin.php <<"EOF"
<?php
use \Foo;
require_once (__DIR__ . '/Bar.php');
$bar = new \Foo\Bar();
?>
EOF
... then everything works:
+ php testin.php
In Bar constructor
... but then, what is the point of use, if I have to repeat the full namespace path when doing $bar = new \Foo\Bar();? (if I don't explicitly write \Foo\Bar(), then class Bar cannot be found...)
 
     
    