php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72483 General error with inheritance/implementation and returning type
Submitted: 2016-06-24 06:51 UTC Modified: 2016-06-24 12:16 UTC
From: alan dot g-l at live dot fr Assigned: cmb (profile)
Status: Duplicate Package: Reproducible crash
PHP Version: 7.0.8 OS: Debian 8.5
Private report: No CVE-ID: None
 [2016-06-24 06:51 UTC] alan dot g-l at live dot fr
Description:
------------
If you want to build a function that force to return its own instance, you simply set it as returning self.

But when you want to extend it, then PHP will said that our new class is not compatible with the parent one if we are overloading it.
So maybe the "static" keyword is the answer, as it will be evaluated when executing? Wrong, PHP does not except the "static" keyword.

This problems are the same for both class inheritance and interface implementation.

Test script:
---------------
// Interfaces
// Sample 1
// with "self" keyword
interface MyInterface {
  public function myFunction(): self;
}

class MyClass implements MyInterface{
  public function myFunction(): self {
    return $this;
  }
}

// Fatal error: Declaration of MyClass::myFunction(): MyClass must be compatible with MyInterface::myFunction(): MyInterface

// Sample 2
// with "static" keyword
interface MyInterface {
  public function myFunction(): static;
}

class MyClass implements MyInterface {
  public function myFunction(): static {
    return $this;
  }
}

// Parse error: syntax error, unexpected 'static' (T_STATIC) 

// Classes and inheritance
// Sample 3
// with "self" keyword
class MyClass {
  public function myFunction(): self {
    return $this;
  }
}

class MyClass2 extends MyClass {
  public function myFunction() : self {
    return $this;
  }
}

// Fatal error: Declaration of MyClass2::myFunction(): MyClass2 must be compatible with MyClass::myFunction(): MyClass

// Sample 4
// with "static" keyword
class MyClass {
  public function myFunction(): static {
    return $this;
  }
}

class MyClass2 extends MyClass {
  public function myFunction(): static {
    return $this;
  }
}

// Parse error: syntax error, unexpected 'static' (T_STATIC)

Expected result:
----------------
I think that the "self" keyword should work, as MyClass implements MyInterface (or MyClass2 extends MyClass), so the first one is an instance of the second one.

Anyway, we can imagine that my asumption is false. So why that "static" word would not work here?


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-06-24 12:16 UTC] cmb@php.net
-Status: Open +Status: Duplicate -Assigned To: +Assigned To: cmb
 [2016-06-24 12:16 UTC] cmb@php.net
Duplicate of bug #72442.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 13:01:28 2024 UTC