How to Call a Static Method from a Class If All I Have Is a String of the Class Name

How can I call a static method from a class if all I have is a string of the class name?

Depending on version of PHP:

call_user_func(array($class_name, 'doSomething'));
call_user_func($class_name .'::doSomething'); // >5.2.3

PHP call a static method of a class by class name

Check out this post. How can I call a static method on a variable class?

It look like your code is ok in php 5.3. There's also some ideas how to deal with your problem if you are < 5.3.

Calling a static method with self vs. class name

You make a few statements that aren't entirely correct:

Calling Python static methods using the class name is more common

It's not more common, it's the only way to do so from outside the class. i.e.:

class MyClass:
@staticmethod
def a_method():
pass

MyClass.a_method()

In this example, self.a_method() would not work, as self would not refer to an instance of MyClass.

calling a static method with self is the same as ClassName.static_method(self), where self would be ignored by the static method

That's not actually the case, for example:

class MyClass:
@staticmethod
def a_method():
pass

def another_method(self):
# this is fine
self.a_method()
# this causes an error, as .a_method expects no arguments
MyClass.a_method(self)

self simply refers to the instance of the class that called an instance method (which has the self argument, which doesn't even have to be called self - it's just whatever the first parameter is called, self is the convention.

You can call static methods on self, because self is an instance of the class that has the static method, and thus has the method. You can also call static methods on classes directly, because a static method doesn't require an object instance as a first argument - which is the point of the static method.

You're fine using self.a_method() where you like, just keep in mind that self will refer to an object of the class the object was instanced as, not the specific class you mention.

For example:

class ClassA:
@staticmethod
def a_method():
print('a')

def another_method(self):
# prints whatever a_method for the class of self prints
self.a_method()
# always prints 'a', as a_method for ClassA prints 'a'
ClassA.a_method()

class ClassB(ClassA):
@staticmethod
def a_method():
print('b')

a = ClassA()
a.another_method()
b = ClassB()
b.another_method()

The output:

a
a
b
a

So, you see, there is a difference between calling from self. and from Class.

How to call a JavaScript static class method when the class name and method name are strings?

Since the answer is buried in the comments to the question, I figured I should go ahead and post it here as an actual answer, so future viewers can easily find the answer.

The answer is: In JavaScript, it's not possible to invoke a method in a class that was loaded from an ES6 module, where the name of the class is in a string.

PHP variable class static method call

The problem is that you are access are property from a class in the first useage, but then in the second try you are parsing the value of the class property (into $c), what is a classname as string, and this can used for static calls to static class functions. The first try, trys to access the static method on an string (the class property).

class a {
static function b(){echo'works';}
}
$a='a';
$a::b();

But the real issue of the error is, that this ->FooBar:: is an syntax error in PHP.

Why can I call this static method using the class name but not using a class instance?

Your confusion is a very natural one, and it is exacerbated by the design of C# in this respect. I'll try to explain as we go, and I'll reformulate your questions to be easier to answer:

Is class synonymous with object?

No. Let's be very, very clear on this point. "Object" has a specific meaning in C#. An object is always an instance of a type. There are two broad kinds of object in C#: reference types which are copied by reference, like string and value types which are copied by value, like int.

Later you will learn about boxing, which is the mechanism by which an instance of value type may be used in a context that expects a reference, but don't worry about that for now.

In C# a class defines a reference type. Instances of that class are objects. The class itself is not an object.

The justification for this comes from the real world. The class "all objects which are newspapers" is not itself a newspaper. The class "all people who speak French" is not itself a French speaker. It is a category error to confuse a description of a set of things with a specific example of the thing!

(You may wish to examine closely the design of prototype inheritance languages such as JavaScript. In JS we make a specific object that is the prototypical example of a kind of thing, and we make a constructor object that represents the factory for new examples of that kind of thing; the prototype and the constructor work together to make new instances, and both are genuinely objects. But again, your question is about C#, so let's stick to that for now.)

are classes used in creating objects?

Yes. We instantiate a class with new; since all classes are reference types, new produces a reference to a novel object.

So why does the error disappear when i use the class name, if classes are essentially objects?

Classes are not objects, but I understand your confusion. It certainly looks like the class name is being used in a context where you would expect an object. (You might be interested to examine closely the design of languages like Python where classes are objects, but your question is about C# so let's stick to that.)

To resolve this confusion you need to understand that the member access operator, also called the "dot operator", in C# is one of the most flexible and sophisticated operators. This makes it easy to use but hard to understand!

The key thing to understand is that the member access operator always has this form:

  • On the left of the dot is an expression that evaluates to a thing that has members
  • On the right of the dot is a simple name.
  • Though it is possible, and common, for thing to be an object and thing.name to be an object, it is also possible for either or both to not be an object.

When you say p.Main the compiler says "I know that p is an instance of Program, and I know that Main is a name. Does that make sense?"

The first thing the compiler does is verifies that Program -- p's type -- has an accessible member Main, which it does. At this point overload resolution takes over, and we discover that the only possible meaning of Main is a static method. This is likely a mistake because p is an instance, and we're attempting to invoke a static through the instance. C#'s designers could have allowed this -- it is allowed in other languages. But since this is a likely mistake, they disallowed it.

When you type Program.Main, Program is not an object. The compiler verifies that Program refers to a type and types have members. Once again, overload resolution takes over and it determines that the only possible meaning is that Main is being invoked. Since Main is static and the receiver -- the thing on the left of the dot -- refers to a type, this is allowed.

Maybe it's just not being explained properly in this class I'm taking.

I edit technical books and other course materials and a great many of them explain these concepts very poorly. Also a great many instructors have vague and confused notions about the relationships between classes, objects, variables, and so on. I encourage you to question your instructor closely on these matters until you are satisfied with their explanations.

That said, once you have a solid grasp on these matters then you can start to take shortcuts. As expert C# programmers we say "p is an object which..." because we all know that we mean "p is a variable, the value of which is a reference to an object which..."

I think it is helpful for the beginner to spell it out, but you will very quickly become more relaxed about it.

One other thing that you did not ask but is important:

What about reflection?

.NET has a reflection system which allows you to take things that are not objects, like classes, structs, interfaces, methods, properties, events, and so on, and obtain an object which describes them. (The analogy being that a mirror image is not reality but it sure looks like it enough to understand reality.)

It is important to remember that the reflection object is not the class. It is an object which describes the class. If you use reflection in your program like this:

Type t = typeof(Program);

then the value of t is a reference to the Type object that describes the characteristics of class Program. You could inspect that object and determine that there was a MethodInfo for method Main, and so on. But the object is not the class. You cannot say

t.Main();

for example. There are ways to invoke methods via reflection, but it is a mistake to think of the Type object as being the class. It reflects the class.

Another question you did not ask but is germane to your education:

What you're saying here is that values are instances of objects, but certain programming language constructs such as classes are not objects that can be manipulated like values. Why is it that some programming language constructs in C# are "first class" -- they can be treated as data manipulated by the program -- and some are "second class", and cannot be so manipulated?

That question gets to the crux of language design itself. All language design is a process of examining past languages, observing their strengths and weaknesses, coming up with principles that attempt to build on strengths while mitigating weaknesses, and then resolving the countless contradictions entailed when principles come into conflict with each other.

We all want a camera that is lightweight, inexpensive, and takes great pictures, but as the saying goes, you can only have two. The designers of C# were in a similar position:

  • We want languages to have a small number of concepts that must be understood by the novice. Moreover, we achieve this by unifying disparate concepts into hierarchies; structs, classes, interfaces, delegates and enums are all types. if, while, foreach are all statements. And so on.
  • We want to be able to build programs that manipulate values that are important to the developer in powerful ways. Making functions "first class" for example opens up powerful new ways to program.
  • We want programs to have little enough redundancy that developers do not feel like they are forced into unnecessary ceremony, but sufficient redundancy that humans can understand the program as written.

And now the big ones:

  • We want the language to be general enough to allow line-of-business developers to write programs that represent any concept in their business domain
  • We want the language to be understandable by machines to the extent that the machines can find likely problems before the program even runs. That is, the language must be statically analyzable.

But like the camera, you can't have all of these at once. C# is a general-purpose programming language designed for programming in the large with a strong static type checker for finding real-world mistakes before they make it into production. It is precisely because we want to find the sort of error you're encountering that we do not allow types to be treated as first-class values. If you treat types as first class then huge amounts of static analysis capability goes out the window!

Other language designers made completely different choices; the consequences of Python saying "classes are a kind of function, and functions are a kind of object" dramatically moves the language towards our desired goal of hierarchical simplicity and first-class treatment of language concepts, and dramatically away from ability to statically determine correctness. That's the right choice for Python, but not for C#.

Is it possible to call a static method of another class from a non static method without instance in java?

firstly modifier static not allowed at class pgm.

If you want to call func and x in class legs.

You must use public final then your class name and declare all member of class as static.

After then you need to get reference for class pgm.

So your code will be

  import java.io.*;
import java.util.*;
public final class pgm
{
static int x,v;
static void func()
{
System.out.println("Function run");
}
}

class egs
{
public static void main(String args[])
{
pgm p=null; //ref here
p.func(); // use ppm func here
try
{
p.x=10;
p.func();
}
catch(NullPointerException e)
{
System.out.println("Null caught");
}

}
}

You would get what you want.

Never get confused static used for compile whole block, method, variable at compile time so you can call anything which is static at run time without any instantiation (using new).

Right way I provide you above.

is there any difference between invoking a static method with class name and invoking a static method with an object in java?

Internally, new ClassName().staticMethod(); is considered as ClassName.staticMethod(). So there is no difference. It just causes confusion.
Consider an example

public class StaticDemo {

static int staticVar = 10;

public static void main(String [] args){

System.out.println(new StaticDemo().staticVar);
System.out.println(StaticDemo.staticVar);

}

}

This outputs

10
10

`

even if you write new StaticDemo().staticVar, it will be considered as StaticDemo.staticVar. So there is no difference at all and always use the Class notation to avoid confusion.



Related Topics



Leave a reply



Submit