Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing sibling method

Tags:

oop

php

I've been searching for an answer all day, but I can't seem to find one. Sorry if I don't make much sense, I'm losing my mind over this.

Here's what I'm trying to do:

abstract class Parent {
    abstract public function Test();
}
class Child1 extends Parent {
    abstract public function Test() {
        echo "Test!";
    }
}
class Child2 extends Parent {
    public function Test2() {
        echo "Test2!";
        $this->Test(); // Child1::Test();
    }
}

Again, sorry if I'm not making much sense. I will try to explain more if you need me to.

like image 978
Matt Avatar asked Jun 06 '26 12:06

Matt


2 Answers

You are missing the concept of abstract classes and methods.

Abstract classes

Abstract classes are classes that define some basic behavior and cannot be instantiated. They are designed to be subclassed.

Abstract methods

These are methods that need to be implemented by the extending class. Like interfaces abstract methods define behavior without an implementation.

Your code

In your code you declared an abstract class with an abstract method.

abstract class Parent {
    public abstract function Test();
}

When another class subclasses Parent it must implement the abstract method making it concrete.

class Child extends Parent {
    public function Test() {
        echo "Test!";
    }
}

Accessing sibling method

A class or instance has no concept of a sibling. A class cannot know who subclasses its parent and access it in a static way.

like image 86
Bart Avatar answered Jun 08 '26 03:06

Bart


It's not an OOP pattern, and not available in any OOP language that I kow of (except for introspection magic): Child2 do not know anything (and does not have to) about Child1 class. they could be defined independently.

I think that at this point you should explain what your needs are. I guess we could help you ,with some design pattern.

like image 28
Raphael Jolivet Avatar answered Jun 08 '26 03:06

Raphael Jolivet