M
M
Max Ba2019-02-07 15:58:06
PHP
Max Ba, 2019-02-07 15:58:06

Is it possible to split a class like this?

Guys, do not criticize strictly) The question is solely on grammar.
I have a class with two methods. And I suddenly decided to separate the methods into different files. Don't ask "why me". I'm interested in the implementation! Am I doing the right thing overall?

class A{
  public $val = 10;
  public function method1(){
    $m2 = new B();
    return $m2->method2();
  }
}

class B extends A{
  public function method2(){
    return $this->val + 1;
  }
}

$a = new A();
echo $a->method1();

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
hack504, 2019-02-07
@phpcoder81

If you need to work within a single class instance, then you can try this

class A{
  public $val = 10;
  public function method1(){
    $m2 = new B($this);
    return $m2->method2();
  }
}

class B {
  public function __construct($obj) {$this->obj = $obj;}
  public function method2(){
    return $this->obj->val + 1;
  }
}

$a = new A();
echo $a->method1();

True, all methods and properties of the class should only be public, but apparently this is not critical.

I
ipokos, 2019-02-07
@ipokos

It will work. If you describe what the goal is, perhaps there will be a more adequate solution. (eg traits )
But if you "share" a class, because it has a lot of methods and you want to structure them, which means something went wrong initially.

P
Pavlo Ponomarenko, 2019-02-07
@TheShock

Basically, you can. But what Class A knows about its heir, Class B, smells sooooo creepy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question