SkyLar
SkyLar

Reputation: 93

class initiation with php

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?

Upvotes: 0

Views: 318

Answers (4)

Tom Haigh
Tom Haigh

Reputation: 57815

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();

Upvotes: 0

too much php
too much php

Reputation: 90998

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();

Upvotes: 1

Bart Verkoeijen
Bart Verkoeijen

Reputation: 17743

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();

Upvotes: 2

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

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.

Upvotes: 0

Related Questions