Call Child Method in Main Class - php

I wanna call a Child Method in Main Class without declare new child();
class main {
function __construct() {
}
public function test() {
}
}
class child extends main {
function __construct() {
}
function childmethod() {
return "test";
}
}
$main = new main();
$main->childmethod();
best wishes

Make class as abstract and declare the method you want to call from child class as abstract.
abstract class main {
function __construct() {
}
public function test() {
return "test";
}
abstract function childmethod();
}
class child extends main {
function __construct() {
}
function childmethod() {
return "childmethod";
}
}
$main = new child();
echo $main->childmethod();// echoes childmethod
echo $main->test();// echoes test

If I correctly understand what you're asking for, you cannot do it and it's a mistake in the project idea.
If you need to call a child method in the parent, it means the method should go in the parent.
There's no way to call a method of an object without instantiate the object, unless you create a static method

Related

calling parent constructor inside child constructor

I am just curious to know that if its a good idea to create a child class constructor just for calling parent constructor.
class A {
public function __construct() {
echo 'I am in: '.__CLASS__.'<br/>';
}
public function getData() {
echo 'I am in: '.__METHOD__.'<br/>';
}
}
class B extends A {
public function __construct() {
parent::__construct();
echo 'I am in: '.__CLASS__.'<br/>';
}
public function getDataFromB(){
echo 'I am in: '.__METHOD__.'<br/>';
}
}
$objB = new B();
$objB->getDataFromB();
Now in following example we can achieve the same:
class A {
public function __construct() {
echo 'I am in: '.__CLASS__.'<br/>';
}
public function getData() {
echo 'I am in: '.__METHOD__.'<br/>';
}
}
class B extends A {
public function getDataFromB(){
echo 'I am in: '.__METHOD__.'<br/>';
}
}
$objB = new B();
$objB->getDataFromB();
Question:
Is it a good idea to create a child constructor only for invoking parent constructor or there are any other advantages of doing so?
The behavior of __construct calls in classes is:
If class has its' own __construct - it will be called
If class does not have its' own __construct - parent __construct (if it exists) will be called.
So, if you create a __construct in a child class, parent __construct will not be called unless you explicitly point it with parent::__construct().
So, if nothing serious will happen in a child __construct - you can omit it and parent __construct will be called.
On the other side - if you do some additional initialization or other actions in child __construct, then it will not call parent::__construct unless you explicitly point it.

Inheriting instance in PHP

I try to call getTest() function inside Child class.
First I initialize instance of Ext class so I assume main property $ext should now contain it. But Child class does not inherit it and obtained error message is:
Call to a member function getTest() on a non-object
Where is the issue?
<?php
$A = new Main;
class Main
{
protected $ext = null;
function __construct()
{
$this->ext= new Ext();
new Child;
}
}
class Child extends Main
{
function __construct()
{
echo $this->ext->getTest();
}
}
class Ext extends Main
{
public function getTest()
{
return "cool";
}
}
?>
I know that to solve it other way I can use:
class Child
{
private $Main;
function __construct( &$Main ) { ... }
}
but I would like to understand why that does not work..
At the moment on construct the object the atribute don't have a value yet.
You need call to the parent constructor before use the attribute
function __construct()
{
parent::__construct();
echo $this->ext->getTest();
}

Can I make a function child of another Class without extends Class?

My Class is independant from another Class.
Inside my Class, a function is doing the same but refined job as a function in another Class. Can I use parent:: function_in_another_class() and get my function join that parent funciton's job flow?
No.
In PHP you can only extend from none or one class. As you write both classes are independent to each other, there is no information where to find the one or the other class.
But what you're looking for is probably this:
class A
{
function myFunction() {}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
public function myFunction()
{
$this->a->myFunction();
}
}
If any class method already doing the same thing why would you bother call join it?
You can not do it. If you want the same job flow best way to do is to instantiate the other class and invoke that very same method. Thats why we use OOP.
See the example,
interface Fable()
{
public function f();
}
class OtherClass implements Fable
{
public function f()
{
// job flow
}
}
class MyClass
{
private $fable;
public function __construct(Fable $f)
{
$this->fable = $f;
}
public function method1($args){
return $this->fable->f($args);
}
}
If the current class is a child of another class, yes, you can. parent references to the parent class.
From php.net:
<?php
class A {
function example() {
echo "I am A::example() and provide basic functionality.<br />\n";
}
}
class B extends A {
function example() {
echo "I am B::example() and provide additional functionality.<br />\n";
parent::example();
}
}
$b = new B;
// This will call B::example(), which will in turn call A::example().
$b->example();
?>
The best you can do here is to extend Class B from Class A
Class B extends Class A
But, you can also:
class ClassA {
function do_something($args) {
// Do something
}
}
class ClassB {
function do_something_inclassA($args) {
classA::do_something($args);
}
}
Important: calling classa::do_something(); is a static call, in other words with error reporting E_STRICT you will get a static notice warning because function do_something() is not static function do_something()
Also, calling this function statically (i.e. classa::do_something()) means that class a's function cannot refer to $this within it

Require a method in parent class to be called in PHP

As the title states, I'm trying to make a method in a parent class required. Although, I suppose it could be any class. For instance:
class Parent
{
function foo ()
{
// do stuff
}
}
class Child extends Parent
{
function bar ()
{
// do stuff after foo() has ran
}
}
Basically, I want foo() to be required to run or Child class doesn't run and returns an error or redirects to a different page. I could call the function, but I'm wondering If I can make it a requirement when extending the parent class.
If you leverage abstract classes and methods, you can force subclasses to implement the missing methods.
abstract class ParentClass
{
public function foo ()
{
// do stuff
$this->bar();
}
abstract protected function bar();
}
class Child extends ParentClass
{
protected function bar()
{
// does stuff
}
}
Subclasses that don't implement bar() will generate a fatal error.
What you should probably do is override Parent::foo() and then call the parent method in the overridden method like so:
class Parent
{
function foo ()
{
// do stuff
}
}
class Child extends Parent
{
function foo ()
{
if(!parent::foo()) {
throw new Exception('Foo failed');
}
// do child class stuff
}
}
Why not just set a boolean in function foo() that acts as a flag. Check to see if it has been set in the child class/functions, and you're all set.
Have the child call the function from the parent in the construct.
class Child extends Parent
{
function bar ()
{
// do stuff after foo() has ran
}
function __construct(){
parent::foo();
}
}
As already mentioned, it sounds like you want foo() to be abstract, forcing child classes to override it.
Any class containing an abstract class in PHP requires your parent class to be abstract too. This means it can't be instantiated (constructed), only derived / sub-classed. If you try to instantiate an abstract class the compiler will issue a fatal error.
http://php.net/manual/en/language.oop5.abstract.php
See the code in Peter Bailey's answer.
If you're not actually initializing any code within parent class you should use an object interface. Interface methods have to be implemented or the script will throw a fetal error.
More information on them can be found: http://us3.php.net/interface.
I think this might be the only way of implementing such functionality, as I don't think there is a built in solution.
class Parent
{
public $foo_accessed = FALSE;
function foo ()
{
$this->foo_accessed=TRUE;
// do stuff
}
}
class Child extends Parent
{
function bar ()
{
if($this->foo_accessed==TRUE) {
// do stuff after foo() has ran
} else {
// throw an error
}
}
}
Do not depend on other methods. Make sure they've ran.
class Parent
{
function foo()
{
// do stuff
}
}
class Child extends Parent
{
private function bar()
{
// do child class stuff
}
public function doFooBar()
{
parent::foo();
$this->bar();
}
}
Following approach will only ever complain after all processing has been done - however if that is fair to you it will definately make sure foo() has been called in the parent class or otherwise trigger a condition that you can act upon.
class DemandingParent {
private $hasFooBeenCalled = false;
public function foo() {
$this->hasFooBeenCalled = true;
/* do Stuff */
}
public function __destruct() {
if (!$this->hasFooBeenCalled) {
throw new Exception("Naughty Child! Call your parent's foo b4 you speak up!");
}
}
}

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

Categories