In php we can access static member functions using class objects. Can someone please tell any practicle use of this feature - static

In php we can call static member functions using class objects. For example
class Human
{
public static function Speak()
{
echo "I am a human.";
}
}
$human = new Human();
$human->Speak();
What we would expect is that a static member function can only be called using the class name and not the class instance variable (object). But what i have seen while programming is that php allows calling a static member function using the class object also. Is there any practical use or some important reason that this feature has been provided in php ?
This feature exists in java and c++ also. Thanks Oli for pointing this out in your response.

This is the same as in other OO languages, such as C++ and Java. Why would you want the interpreter to prevent this?
UPDATE
My best guess for this (and this is only a guess) is "for convenience". In essence, why should the user of your class necessarily care whether a given member function is static or not? In some circumstances, this will certainly matter; in others, maybe not. I'm not saying this is a great justification, but it's all I can come up with!

it allows you to abstract from the particular definition of the method, so that for example if you had to turn it into a static one at some point, you don't have to rewrite all the method calls!

I can't answer for PHP, (or really for anything) but consider this hypothetical C++:
class base{
public:
static void speak(){cout<<"base\n";}
};
class sub :public base {
public:
static void speak(){cout<<"sub\n"; }
};
int _tmain(int argc, _TCHAR* argv[]){
base *base1 = new base();
base1->speak();
sub *sub1 = new sub();
sub1->speak();
base *sub2 = new sub();
sub2->speak();
((sub*)sub2)->speak();
}
The output would be:
base
sub
base
sub
I'm sure it could be useful... maybe helping you determine which class's static method you should call based on the object currently in hand.

Related

Is it bad to wrap singleton instance methods in static methods?

Is there a con to implementing a singleton that wraps instance methods with static ones?
For example:
public void DoStuff() { instance._DoStuff(); }
private void _DoStuff() {
...
}
And of course instance would be static. But it would be nicer to call:
Singleton.DoStuff();
Instead of:
Singleton.GetInstance().DoStuff();
I think it depends.
First the GetInstance() really should be used for getting an object back and then using that else where in your code. The Singleton should just help guarantee a single instance of that object exists.
Next if you want to make DoStuff static go ahead, though you have to know to call it that way everywhere else in your code.
So you really have this difference:
var instance = Singleton.GetInstance();
...
instance.DoStuff ()
Vs
Singleton.DoStuff ()
This means that you can pass a singleton object around and not have to know static calls.
Also, I have to mention that Singletons if not used properly can lead to a nightmare in unit testing: http://misko.hevery.com/2008/08/25/root-cause-of-singletons/

How Mybatis (iBatis) read my private variable?

I was wondering how Mybatis get the private variable in Java.
For example:
Let's say we have a Java class called Foo:
public class Foo{
private int foolID;
public Foo(int foolID){
this.foolID = foolID;
}
}
And let's create XML mapper for insert.
<insert id="insert" parameterType="Foo">
insert into foo_table (id)
values (#{foolID});
</insert>
Let's say there are FooDAO java class and FooMapper java interface for this insert.
My question is how come foolID is readable even without Getter (Even if there is a getter method for foolID, I never specify what the getter is...). It seems like magic to me, and I know there is no magic for programming... :)
The only way I can think of is reflection.
Thanks for your help in advance.
That's correct, reflection is used to access private fields, but only if accessing private fields is not restricted.
Seams like reflection is used heavily not just to access private fields but to invoke setters getters etc.

Is there a #visibility package concept in PHPDoc / PHPStorm?

I have a domain model written in PHP, and some of my classes (entities inside an aggregate) have public methods, which should never be called from outside the aggregate.
PHP does not have the package visibility concept, so I'm wondering if there is some kind of standardized way to define #package and #visibility package in the docblocks, and to have a static analysis tool that would report violations of the visibility scope.
I'm currently trying out PHPStorm, which I've found very good so far, so I'm wondering if this software has support for this feature; if not, do you know any static code analysis tool that would?
The closest parallel to this line of thinking that I see in PHP's capability is using "protected" scope rather than public for these kinds of methods. Granted, that requires using inheritance to grant access to the protected items. In my years of managing phpDocumentor, I've never encountered anything else that attempts to mimic that kind of "package scope" that I remember from my Java days.
If the entities within your aggregate root should not be modifiable without going through the aggregate root, then the only means you have to control that is making the entity a private or protected member so that all modifications to the entity have to go through the aggregate.
class RootEntity {
private $_otherEntity;
public function DoSomething() {
$this->_otherEntity->DoSomething();
}
public function setOtherEntity( OtherEntity $entity ) {
$this->_otherEntity = $entity;
}
}
Someone can still always do:
$otherEntity = new OtherEntity();
$otherEntity->DoSomethingElse();
$rootEntity->setOtherEntity($otherEntity);
Though, I guess you could use the magic __call() method to prohibit setting of the _otherEntity anywhere except during construction. This falls under total hack category :)
class RootEntity {
private $_otherEntity;
private $_isLoaded = false;
public function __call( $method, $args ) {
$factoryMethod = 'FactoryOnly_'.$method;
if( !$this->_isLoaded && method_exists($this,$factoryMethod) {
call_user_func_array(array($this,$factoryMethod),$args
}
}
public function IsLoaded() {
$this->_isLoaded = true;
}
protected function FactoryOnly_setOtherEntity( OtherEntity $otherEntity ) {
$this->_otherEntity = $otherEntity;
}
}
So, from there, when you build the object, you can call $agg->setOtherEntity($otherEntity) from your factory or repository. Then when you are done building the object, call IsLoaded(). From there, nobody else will be able to introduce a new OtherEntity into the class and will have to use the publicly available methods on your aggregate.
I'm not sure if you can call that a "good" answer, but it's the only thing I could think of to truly limit access to an entity within an aggregate.
[EDIT]: Also, forgot to mention...the closest for documentation is that there is an #internal for phpdoc:
http://www.phpdoc.org/docs/latest/for-users/tags/internal.html
I doubt that it will modify the IDE's code completion, however. Though, you could probably make a public function/property but label it as "#access private" with phpdoc to keep it from being in code completion.
So far, PHPStorm does not seem to provide this feature.

Static and Normal class combined in one class

I am trying my best to explain the situation. I hope, what I wrote, is understandable.
We already have class defined like
public ref class TestClass
{
public:
TestClass();
virtual ~TestClass();
protected:
Car* m_car;
}
TestClass is managed C++ and Car is unmanaged C++.
So far so good, but now I need to make static object of TestClass also. So I modify the code like below
public ref class TestClass
{
private:
static TestClass^ s_test = nullptr ;
public:
TestClass();
virtual ~TestClass();
static TestClass^ Instance();
protected:
Car* m_car;
}
When I want to use static instant of the class, I just get it from calling
TestClass staticobj = TestClass::Instance();
Elsewhere, just call
TestClass normalobj = gcnew TestClass();
Instance function is creating s_test static object and returns it.
TestClass ^ TestClass::Instance()
{
if(s_test == nullptr)
{
s_test = gcnew TestClass();
s_test->m_car = new Car();
}
return s_test;
}
Is it a good approach?
Is there any other better approach to accomplish same thing?
Edit :
FYI Above code works.
I combined Krizz and Reed Copsey’s solutions. That solve independent Singleton and memory leak.
Here is my sample code,
Special Singleton class derived from test class,
public ref class SpecialSingletonTestClass: public TestClass
{
private:
static SpecialSingletonTestClass ^ s_ SpecialSingletonTestClass = nullptr;
public:
SpecialSingletonTestClass ();
static SpecialSingletonTestClass ^ Instance();
};
Changed the testclass so it has now one more finalizer function.
public ref class TestClass
{
public:
TestClass ();
virtual ~ TestClass ();
! TestClass ();
protected:
Car* m_car;
}
I tested above pattern , it worked.
Thanks you guys,
L.E.
Is it a good approach?
I would probably not consider this a good approach, as you're making a single class both a singleton and a normal class that you can instance directly.
Typically, if you need a singleton, this would preclude the need or desire to be able to instantiate the class.
If you truly need to have a way to have a "global" instance of this class, I would encapsulate that in a separate class which implements the singleton. This would, at least, make it clear that you are dealing with something that's a single instance in that case. I would not mix both use cases into a single class.
Well, actually there is an issue with memory leaks in your code.
You declare only virtual ~TestClass(); which, for managed classes, are internally turned by C++/CLI compiler into implementation of IDisposable.Dispose().
Therefore, if you put delete car into it, it will be called only if you delete test_class or, e.g. wrap into using (TestClass tst) {} block when using from C#.
It will not be called when object is GCed!
To be sure it is called you need to add finalizer to your class !MyClass(); which is turned by compiler into virtual void Finalize() and thus non-deterministically called when GC is freeing an object.
And it is the only way to free m_car of singleton object.
Therefore, I suggest:
TestClass()
{
m_car = new Car();
}
~TestClass()
{
if (m_car)
delete m_car;
m_car = NULL;
}
!TestClass()
{
if (m_car)
delete m_car;
m_car = NULL;
}
I'm unsure as to what situation you could possibly be in that would require both singleton-style semantics and normal creation semantics for the same class.
As far as what you've coded though, it looks completely fine. My only comments would be that your Instance() function shouldn't need to perform construction on Car, the Instance() function should just call the default constructor of TestClass which should do all that.
EDIT
In reference to:
#crush . The class is already define i just need to get static object of it. Singleton means only one object of the class, but in this case, class have multiple normal object. But i want to use only one object of this class for one specific goal only for limited period of time. – L.E. 2 mins ago
A singleton is (usually) a sign of bad design - alot of people call it an anti-pattern actually. Chances are if you just need this one single specific instance of this class for a limited period of time there are some issues:
Singleton design is made for static-style existence - the variable will live for the scope of your program after lazily initialized.
Allowing global access will move your code towards spaghetti logic. You'd be better off dynamically allocating the one you need and passing the pointer to it to where you need it to be. A shared_ptr would be good for this.
You should find a way around the singleton-style implementation in this case even if it's more work for you - it'll almost certainly be better design.

Creating New Array with Class Object in GWT

I would like to create a new array with a given type from a class object in GWT.
What I mean is I would like to emulate the functionality of
java.lang.reflect.Array.newInstance(Class<?> componentClass, int size)
The reason I need this to occur is that I have a library which occasionally needs to do the following:
Class<?> cls = array.getClass();
Class<?> cmp = cls.getComponentType();
This works if I pass it an array class normally, but I can't dynamically create a new array from some arbitrary component type.
I am well aware of GWT's lack of reflection; I understand this. However, this seems feasible even given GWT's limited reflection. The reason I believe this is that in the implementation, there exists an inaccessible static method for creating a class object for an array.
Similarly, I understand the array methods to just be type-safe wrappers around JavaScript arrays, and so should be easily hackable, even if JSNI is required.
In reality, the more important thing would be getting the class object, I can work around not being able to make new arrays.
If you are cool with creating a seed array of the correct type, you can use jsni along with some knowledge of super-super-source to create arrays WITHOUT copying through ArrayList (I avoid java.util overhead like the plague):
public static native <T> T[] newArray(T[] seed, int length)
/*-{
return #com.google.gwt.lang.Array::createFrom([Ljava/lang/Object;I)(seed, length);
}-*/;
Where seed is a zero-length array of the correct type you want, and length is the length you want (although, in production mode, arrays don't really have upper bounds, it makes the [].length field work correctly).
The com.google.gwt.lang package is a set of core utilities used in the compiler for base emulation, and can be found in gwt-dev!com/google/gwt/dev/jjs/intrinsic/com/google/gwt/lang.
You can only use these classes through jsni calls, and only in production gwt code (use if GWT.isProdMode()). In general, if you only access the com.google.gwt.lang classes in super-source code, you are guaranteed to never leak references to classes that only exist in compiled javascript.
if (GWT.isProdMode()){
return newArray(seed, length);
}else{
return Array.newInstance(seed.getComponentType(), length);
}
Note, you'll probably need to super-source the java.lang.reflect.Array class to avoid gwt compiler error, which suggests you'll want to put your native helper method there. However, I can't help you more than this, as it would overstep the bounds of my work contract.
The way that I did a similar thing was to pass an empty, 0 length array to the constructor of the object that will want to create the array from.
public class Foo extends Bar<Baz> {
public Foo()
{
super(new Baz[0]);
}
...
}
Baz:
public abstract class Baz<T>
{
private T[] emptyArray;
public Baz(T[] emptyArray)
{
this.emptyArray = emptyArray;
}
...
}
In this case the Bar class can't directly create new T[10], but we can do this:
ArrayList<T> al = new ArrayList<T>();
// add the items you want etc
T[] theArray = al.toArray(emptyArray);
And you get your array in a typesafe way (otherwise in your call super(new Baz[0]); will cause a compiler error).
I had to do something similar, I found it was possible using the Guava library's ObjectArrays class. Instead of the class object it requires a reference to an existing array.
T[] newArray = ObjectArrays.newArray(oldArray, oldArray.length);
For implementing an array concatenation method, I also stepped into the issue of missing Array.newInstance-method.
It's still not implemented, but if you have an existing array you can use
Arrays.copyOf(T[] original, int newLength)
instead.

Resources