views:

1434

answers:

5

Hi Just like we do with __ToString, is there a way to define a method for casting?

$obj = (MyClass) $another_class_obj;
A: 

I do not believe there is a overloading operator in PHP to handle that, however:

<?php

class MyClass {

  protected $_number;

  static public function castFrom($obj) {
    $new = new self();
    if (is_int($obj)) {
      $new->_number = $obj;
    } else if ($obj instanceOf MyNumberClass){
      /// some other type of casting
    }
    return $new;
  }
}

$test = MyClass::castFrom(123123);
var_dump($test);

Is one way to handle it.

gnarf
+10  A: 

There is no need to type cast in php.


Edit: Since this topic seems to cause some confusion, I thought I'd elaborate a little.

In languages such as Java, there are two things that may carry type. The compiler has a notion about type, and the run time has another idea about types. The compilers types are tied to variables, whereas the run time engine tracks the type of values (Which are assigned to variables). The variable types are known at compile time, whereas the value types are only known at run time.

If a piece of input code violates the compilers type system, the compiler will barf and halt compilation. In other words, it's impossible to compile a piece of code that violates the static type system. This catches a certain class of errors. For example, take the following piece of (simplified) Java code:

class Alpha {}

class Beta extends Alpha {
  public void sayHello() {
    System.out.println("Hello");
  }
}

If we now did this:

Alpha a = new Beta();

we would be fine, since Beta is a subclass of Alpha, and therefore a valid value for the variable a of type Alpha. However, if we proceed to do:

a.sayHello();

The compiler would give an error, since the method sayHello isn't a valid method for Alpha - Regardless that we know that a is actually a Beta.

Enter type casting:

((Beta) a).sayHello();

Here we tell the compiler that the variable a should - in this case - be treated as a Beta. This is known as type casting. This loophole is very useful, because it allows polymorphism in the language, but obviously it is also a back door for all sorts of violations of the type system. In order to maintain some type safety, there are therefore some restrictions; You can only cast to types that are related. Eg. up or down a hierarchy. In other words, you wouldn't be able to cast to a completely unrelated class Charlie.

It's important to note that all this happens in the compiler - That is, it happens before the code even runs. Java can still get in to run time type errors. For example, if you did this:

class Alpha {}

class Beta extends Alpha {
  public void sayHello() {
    System.out.println("Hello");
  }
}

class Charlie extends Alpha {}

Alpha a = new Charlie();
((Beta) a).sayHello();

The above code is valid for the compiler, but at run time, you'll get an exception, since the cast from Beta to Charlie is incompatible.

Meanwhile, back at the PHP-farm.

The following is valid to the PHP-compiler - It'll happily turn this into executable byte code, but you'll get a run time error:

class Alpha {}

class Beta extends Alpha {
  function sayHello() {
    print "Hello";
  }
}
$a = new Alpha();
$a->sayHello();

This is because PHP variables don't have type. The compiler has no idea about what run time types are valid for a variable, so it doesn't try to enforce it. You don't specify the type explicitly as in Java either. There are type hints, yes, but these are simply run time contracts. The following is still valid:

// reuse the classes from above
function tellToSayHello(Alpha $a) {
  $a->sayHello();
}
tellToSayHello(new Beta());

Even though PHP variables don't have types, the values still do. A particular interesting aspect of PHP, is that it is possible to change the type of a value. For example:

// The variable $foo holds a value with the type of string
$foo = "42";
echo gettype($foo); // Yields "string"
// Here we change the type from string -> integer
settype($foo, "integer");
echo gettype($foo); // Yields "integer"

This feature some times confused with type casting, but that is a misnomer. The type is still a property of the value, and the type-change happens in runtime - not at compile time.

The ability to change type is also quite limited in PHP. It is only possible to change type between simple types - not objects. Thus, it isn't possible to change the type from one class to another. You can create a new object and copy the state, but changing the type isn't possible. PHP is a bit of an outsider in this respect; Other similar languages treat classes as a much more dynamic concept than PHP does.

Another similar feature of PHP is that you can clone a value as a new type, like this:

// The variable $foo holds a value with the type of string
$foo = "42";
echo gettype($foo); // Yields "string"
// Here we change the type from string -> integer
$bar = (integer) $foo;
echo gettype($bar); // Yields "integer"

Syntactically this looks a lot like how a typecast is written in statically typed languages. It's therefore also often confused with type casting, even though it is still a runtime type-conversion.

To summarise: Type casting is an operation that changes the type of a variable (not the value). Since variables are without type in PHP, it is not only impossible to do, but a nonsensical thing to ask in the first place.

troelskn
There is if you want to go from one user defined class to another. There's a way to do this, I've done it before
Josh
Well then, don't keep it to yourself.
VolkerK
I just did post it -- but someone downvoted it. Wonder why
Josh
Variables in PHP are untyped; Only the objects they refer to have types. As such you *can't* typecast a variable in php.
troelskn
That would seem to contradict the PHP manual
Josh
In that case, the manual is wrong.
troelskn
You're wrong troelskn. There is clearly casting ability for primitives. Casting objects is obviously hellish - but it shouldn't be. Telling us that we're wrong, and that the php manual is wrong is just silly.
B T
I realise that my first answer was a bit short. I've added an explanation that hopefully helps to show why the concept of type casting is alien to php.
troelskn
This is an excellent answer. I feel you could improve it by mentioning that in PHP values have types. This is interesting because the value could have its type changed - an Alpha object could be told "become a Beta object". Python and Javascript support this for example (in Python by changing its `__class__` field). However, PHP does not, and has a static class hierarchy. So while it would make sense to allow a PHP value to change its type, it is just not allowed in the language.
Paul Biggar
Good idea, Paul. I've added a section about that.
troelskn
troelskn, I agree, this is an excellent answer and very clearly explains typecasting and the lack of it in PHP.
Josh
+3  A: 

Here's a function to change the class of an object:

/**
 * Change the class of an object
 *
 * @param object $obj
 * @param string $class_type
 * @author toma at smartsemantics dot com
 * @see http://www.php.net/manual/en/language.types.type-juggling.php#50791
 */
function changeClass(&$obj,$new_class)
{
    if(class_exists($class_type,true))
    {
     $obj = unserialize(preg_replace("/^O:[0-9]+:\"[^\"]+\":/i",
      "O:".strlen($class_type).":\"".$new_class."\":", serialize($obj)));
    }
}

In case it's not clear, this is not my function, it was taken from a post by "toma at smartsemantics dot com" on http://www.php.net/manual/en/language.types.type-juggling.php#50791

Josh
Why the downvote?
Josh
That is not a typecast. That is changing the type of the object - not the variable. In PHP, you can't typecast, since variables don't have types.
troelskn
I agree, my function changes the class of the object. WHich is what the question's author intended. And according to the PHP manual, variables *do* have types and typecasting is possible: http://us.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting
Josh
Fair enough; You can change the type of a primitive. But you can't change the type of an object. Regardless of the wording in the manual, variables do *not* have type in php. They refer to values which have type.
troelskn
I see your point -- I'll edit my post to make it clear tha it changes the class of an object.
Josh
Well it doesn't really. It creates a new object of a different class. In a typed language (Such as Java), that is not what a type cast does. There, a type cast simple changes the type of the variable - not the type of the object being referred. There is an (albeit subtle) difference. For example, you can only typecast to types that are valid for the object. You can't typecast to a completely unrelated type.
troelskn
I understand what you're saying.
Josh
A: 

I reworked the function Josh posted (which will error because of the undefined $new_class variable). Here's what I got:

function changeClass(&$obj, $newClass)
{ $obj = unserialize(preg_replace // change object into type $new_class
 ( "/^O:[0-9]+:\"[^\"]+\":/i", 
  "O:".strlen($newClass).":\"".$newClass."\":", 
  serialize($obj)
 ));
}

function classCast_callMethod(&$obj, $newClass, $methodName, $methodArgs=array())
{ $oldClass = get_class($obj);
 changeClass($obj, $newClass);

 // get result of method call
 $result = call_user_func_array(array($obj, $methodName), $methodArgs);
 changeClass(&$obj, $oldClass); // change back
 return $result;
}

It works just like you'd expect a class cast to work. You could build something similar for accessing class members - but I don't think I would ever need that, so i'll leave it to someone else.

Boo to all the jerks that say "php doesn't cast" or "you don't need to cast in php". Bullhockey. Casting is an important part of object oriented life, and I wish I could find a better way to do it than ugly serialization hacks.

So thank you Josh!

B T
Just a note, I would add a thrown exception into changeClass if the class casted to is not a parent class. This would include classes that don't exist. But the code i have above is pretty much the simplest you can get for a working cast that I know of.
B T
The only thing I would use the casting for in php, is to let the IDE know the type of the object.. so the IDE can autocomplete the properties of a class instance.. That's all.
Janov Byrnisson
Well thats all well and good for you Janov, but if you're building a complex interface that isn't incredibly verbose, you sometimes need a little trickery. I *had* to use class casting for a database abstraction layer I created. Otherwise there would have been no way to adequately handle subclassing.
B T
+1  A: 

I think you need to type cast in order to make a better IDE. But php the language itself doesn't need type casting it does however support runtime type changes to the values in the variables. Take a look at autoboxing and unboxing. That's what php inherently does. So sorry no better than already are IDEs.

Syed Zeeshan Shah