Menggunakan Namespace di file php yang berbeda

Menggunakan Namespace di file php yang berbeda (php>5.3)

Mari kita buat test.php yang isinya :

namespace phpstar;

class fooBar {
    public function foo() {
        echo ‘hello world, from function foo’;

    public function bar() {
        echo ‘hello world, from function bar’;

Lalu Buat test2.php yang berada satu folder dengan test.php diatas, yang isinya:

    # location of the file index.php
    # Include the file
    include “test.php”;
    # Option 1: directly prefix the class name with the namespace
    $obj_foobar = new phpstar\fooBar(); //atau bisa juga $obj_foobar = new \phpstar\fooBar();
    # Option 2: import the namespace
    use phpstar\fooBar;
    $obj_foobar = new fooBar();
    # Option 2a: import & alias the namespace
    use phpstar\fooBar as FB;
    $obj_foobar = new FB();
    # Access the properties and methods with regular way

Coba lihat test2.php di browser

Sumber :

tags: php namespace, php namespace in other file, use php namespace in another files, php namespace beda file, namespace in php, php oop, php 5.3

if you are looking for job click Here

jika anda sedang mencari kerja Join disini


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s