How to Check If a Class Inherits Another Class Without Instantiating It

[PHP]How to check if a class inherits another class without instantiating it?

You'll have to use reflection for that, it's pretty large topic:

http://ca.php.net/manual/fr/book.reflection.php

Look at the doc a little, try something and if you still have questions, something more precise, then post another question on that topic.

Check if class is child of class without instantiating

You don't need to instantiate, accessing the .prototype of the possible child will work:

class A {  }
class B extends A { }
class C extends B { }

console.log(C.prototype instanceof A)

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

How can I determine if a class A inherits from class B without instantiating an A object in Ruby?

Sure, just compare the two classes:

if Admin < ActiveRecord::Base
# ...
end

It is interesting to note that while Module#< will return true if Admin inherits from AR::Base, it will return false or nil if that's not the case. false means that it is the otherway around, while nil is for unrelated classes (e.g. String < Range returns nil).

Check if method is static from class without instantiating

Frist get it from the class's namespace, then use isinstance:

def is_staticmethod(cls, m):
return isinstance(cls.__dict__.get(m), staticmethod)

print(is_staticmethod(MyClass, 'method')) # False
print(is_staticmethod(MyClass, 'static_method')) # True

Determine if JavaScript class extends another class

You can use instanceof like this:

MyModel.prototype instanceof Backbone.Model

This works because while there no instantiated instance of MyModel, you don't really care about it, you care about its prototype chain anyway, so you can just check its prototype inheritance.

Note, this will not work for the specific check of

MyModel.prototype instanceof MyModel

That might be fine depending on your use-case, but it you do want that to work, you have two options:

MyModel === MyModel && MyModel.prototype instanceof MyModel

// OR

Object.create(MyModel.prototype) instanceof MyModel


Related Topics



Leave a reply



Submit