Challenge 1 — Solution
Task: Create two files, src/Shop/Product.php (namespace Shop; class
Product with a $name property) and src/Warehouse/Product.php (namespace
Warehouse; class Product with a $stockLevel property). In a third file,
use both classes with aliases via use ... as ... and create one
instance of each, demonstrating no naming collision occurs.
name = $name;
// }
// }
// ?>
// ---- src/Warehouse/Product.php ----
// stockLevel = $stockLevel;
// }
// }
// ?>
// ---- index.php ----
// use Shop\Product as ShopProduct;
// use Warehouse\Product as WarehouseProduct;
//
// $listing = new ShopProduct("Wireless Mouse");
// $stock = new WarehouseProduct(150);
//
// echo $listing->name . "
";
// echo $stock->stockLevel . "
";
// A single-file demonstration of the same underlying idea:
namespace Shop { class Product { public function __construct(public string $name) {} } }
namespace Warehouse { class Product { public function __construct(public int $stockLevel) {} } }
namespace {
use Shop\Product as ShopProduct;
use Warehouse\Product as WarehouseProduct;
$listing = new ShopProduct("Wireless Mouse");
$stock = new WarehouseProduct(150);
echo $listing->name . "
";
echo $stock->stockLevel;
}
?>
Output:
Wireless Mouse
150
Notes:
- Both classes are genuinely named Product, but their fully-qualified
identities - Shop\Product and Warehouse\Product - are completely
distinct, exactly as the chapter's own Logger example demonstrated.
- use Shop\Product as ShopProduct gives the class a shorter, unambiguous
local alias within this one file, so "new ShopProduct(...)" reads
cleanly without needing to write the full namespace every time.
- No fatal "Cannot redeclare class Product" error occurs, even though
both classes share the identical short name - this is precisely the
collision-avoidance benefit namespaces provide.