简体   繁体   中英

php oop - force static method's param to be object of current class

I want to do something like this:

class myclass{

   public static function(__class__ $param){
    // do somthing
   }
}

but __class__ and self::class and nor static is not working.

how should I do this

Just use self :

class A 
{
    public function foo(self $arg)
    {
        var_dump($arg);
    }
}

$a = new A();
$a->foo($a); // object(A)#1 (0) { }

No but, guys, suppose the class is extended tho, he might want to make sure the call to this method uses the child class, not the parent

You can manually restrict this contract for child classes, as shown in other anwsers ( instanceof , etc), but it violates the Liskov substitution principle .

A subclass should always satisfy the contract of the superclass. In good design you should not to narrow the type of arguments in overridden methods.

Widening is allowed: Contravariant method argument type and PHP 7.2 partially supports it.

If you want to enforce this dynamically for subclasses, I'm afraid that's not possible. The best you can do in this case is something like this:

class myclass {
    public static function doStuff(self $a) {
        if (!$a instanceof static) {
            throw new InvalidArgumentException(sprintf('First argument must be of type %s', static::class));
        }
        // Do things with $a
    }
}

What you're asking does not make that much sense in strongly typed languages so I don't think it is something you can do in PHP.

Consider this:

abstract class A {
     public abstract function a(A $myTypeObject);
}

class B extends A { 
     public function a(B $myTypeObject) {
         return $this;
     }
}

Now the problem with this code is that it cannot exist because the overridden function must match the same signature as the parent function. In strongly typed languages a would in fact be an overload so B would have 2 declarations of a , one which accepts A and one which accepts B . However in PHP you'll just get a parse error. If you really want to enforce things you need runtime checking:

abstract class A {
     public function a($myTypeObject) {
          if (!($myTypeObject instanceof static)) {
              throw new \Exception("Invalid type");
          }
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM