tags:

views:

81

answers:

4

I have a class which initiates another class, i'm not concerned with having a reference to the object i only need the method and have to pass in new parameters.

class A {
     __set .....
}

class B extends A {
     $anotherA = new A;
     $anotherA->myName = 'stackoverflow';
}

in short i'd like to have class B extend A, init a new instance of A but i don't want to have to type "new" everytime, i've seen the following syntax:

B::A // something like that

but not sure if how to use it or if that would do what i'm trying to do?

A: 

Since you are extending A in B, you could call the method of class A:

class B extends A {
    public function someMethod() {
        parent::someMethodName();
    }
}

Alternatively, you could create a static method in the class:

class A {
    public static function someStaticMethod() { ... }
}

A::someStaticMethod();

If you really want a new instance of A, you have to use the new operator. That's what it is for.

Jani Hartikainen
+2  A: 

What you could do is define a static method on the class that returns the new instance. It's basically a 'shortcut', but it does exactly the same in the background.

class C {
   public static function instance()
   {
      return new C();
   }

   public function instanceMethod()
   {
      echo 'Hello World!';
   }
}

Now you can call it like:

C::instance()->instanceMethod();
bgever
That's a viable approach but I fail to see how that is any better than using `new`, unless it's supposed to be a singleton or a shortcut such as Doctrine_Query::create()->...
Jani Hartikainen
Sometimes you want to statically retrieve next instances and the only way to do this in PHP <5.3 is using a factory method such as this, or by redefining factory methods in descendants.
Wesley Mason
+1  A: 

Here are some examples of static functions - they can be called without using 'new A' or 'new B'.

class A {
    static function message($msg = 'I am Alpha') {
        echo "hi there, $msg\n";
    }
}

class B {
    static function message() {
        A::message("I am Beta");
    }
}

A::message();
B::message();
too much php
A: 

I would create the instance of A in B's constructor, then you can instantiate B using either its constructor or static B::create(), which just acts as a shortcut. You could make the constructor private if you wanted all instantiation go through create().

class A {
    // __set .....
}

class B extends A {
     public function __construct() {
         parent::__construct();
         $anotherA = new A;
         $anotherA->myName = 'stackoverflow';
     }

     public static function create() {
         return new self();
     }
}


new B();
B::create();
Tom Haigh