Skip to content

Instantly share code, notes, and snippets.

@brzuchal
Last active December 13, 2017 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brzuchal/352ffce2717648f0d43f2d5a0c4bfb7b to your computer and use it in GitHub Desktop.
Save brzuchal/352ffce2717648f0d43f2d5a0c4bfb7b to your computer and use it in GitHub Desktop.
Packages in PHP
<?php
namespace Acme:Animal;
class Cat {
public function __construct() {
echo 'Created ' . self::class . ' from package ' . __PACKAGE__;
}
}
<?php
// package declaration
package Acme declare(strict_types=1);
// future extensions of package
package Acme declare(strict_types=1) {
const VERSION = '1.0';
function createCat() : Animal\Cat {}
}
<?php
namespace Acme:;
class Plant {} // class directly under package namespace
<?php
package Acme declare(strict_types=1) {
const VERSION = '1.0';
function createCat() : Animal\Cat {}
class Plant {}
namespace Animal {
class Cat {}
}
}
package AnotherPackage {
class A {} // here strict_types is default which is 0
}
<?php
use Acme:Animal\Cat;
use Acme:Plant;
use const Acme:VERSION;
use function Acme:createCat;
$cat = new Cat(); // autoload detects package name "Acme" and loads it for eg. from "src/Acme/package.php" or whatever
// it also echoes "Created Acme:Animal\Cat from package Acme"
echo Cat::class; // Acme:Animal\Cat;
$plant = new Plant(); // autoload detects package name "Acme" but it's already been loaded, then do nothing
$anotherCat = createCat(); // same as above
$version = VERSION; // same as above
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment