键入用户定义对象的转换 [英] Type casting for user defined objects

查看:72
本文介绍了键入用户定义对象的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像我们用__ToString一样,是否有一种方法来定义一个方法来转换?

  $ obj = )$ another_class_obj; 


解决方案

没有必要在php中输入cast。 / p>




编辑:因为这个主题似乎引起一些混乱,



在Java等语言中,有两个可能携带类型的东西。编译器有一个关于类型的概念,运行时有另一个关于类型的想法。编译器类型绑定到变量,而运行时引擎跟踪值的类型(分配给变量)。变量类型在编译时是已知的,而值类型仅在运行时已知。



如果一段输入代码违反了编译器类型系统,编译器将barf和停止编译。换句话说,不可能编译一段违反静态类型系统的代码。这捕获了一定类的错误。例如,取以下(简化)Java代码:

  class Alpha {} 

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

如果我们这样做:

  Alpha a = new Beta(); 

我们会很好,因为 Beta Alpha 的子类,因此 类型的 a / code>。但是,如果我们继续:

  a.sayHello 

编译器会给出错误,因为方法 sayHello 不是 Alpha 的有效方法 - 无论我们知道 a 实际上是 Beta



输入类型转换:

 code>((Beta)a).sayHello(); 

这里我们告诉编译器变量 a 应该 - 在这种情况下,被视为 Beta 。这被称为铸造类型。这个漏洞是非常有用的,因为它允许语言中的多态性,但显然它也是各种违反类型系统的后门。为了保持某种类型的安全,因此有一些限制;您只能投射到相关的类型。例如。向上或向下的层次结构。换句话说,你不能投射到一个完全不相关的类 Charlie



注意所有这些都发生在编译器 - 也就是说,它发生在代码运行之前。 Java仍然可以进入运行时类型错误。例如,如果您这样做:

  class Alpha {} 

类Beta扩展Alpha {
public void sayHello(){
System.out.println(Hello);
}
}

类Charlie extends Alpha {}

Alpha a = new Charlie();
((Beta)a).sayHello();上面的代码对编译器是有效的,但在运行时,你会得到一个异常,因为 Beta Charlie 的投射不兼容。





以下内容对PHP编译器有效 - 很高兴将其转换为可执行文件字节码,但您会遇到运行时错误:

  class Alpha {} 

Beta扩展Alpha {
function sayHello(){
printHello;
}
}
$ a = new Alpha();
$ a-> sayHello();

这是因为PHP变量没有类型。编译器不知道什么运行时类型对变量有效,因此它不试图强制它。您不能在Java中显式指定类型。有类型提示,是的,但这些只是运行时合同。以下内容仍然有效:

  //从上面重用类
function tellToSayHello(Alpha $ a){
$ a-> sayHello();
}
tellToSayHello(new Beta());

尽管PHP 变量没有类型,值仍然可以。 PHP的一个特别有趣的方面是,可以改变一个值的类型。例如:

  //变量$ foo包含一个类型为string的值
$ foo =42 ;
echo gettype($ foo); // Yieldsstring
//这里我们改变类型string - > integer
settype($ foo,integer);
echo gettype($ foo); //产生整数

这个特性有时与类型转换混淆,但这是一个错误。类型仍然是值的属性,类型更改发生在运行时 - 而不是在编译时。



更改类型的能力在PHP中也很有限。只能在简单类型(而不是对象)之间更改类型。因此,不可能将类型从一个类改变到另一个类。您可以创建一个新对象并复制状态,但不能更改类型。 PHP在这方面是一个局外人;其他类似的语言将类视为一个比PHP更动态的概念。



PHP的另一个类似的功能是您可以将值克隆为一个新类型,如下所示:

  //变量$ foo包含一个类型为string的值
$ foo =42
echo gettype($ foo); // Yieldsstring
//这里我们改变类型string - > integer
$ bar =(integer)$ foo;
echo gettype($ bar); //产生整数



在语法上看起来很像是类型转换是如何用静态类型语言。因此,它也经常与类型转换混淆,即使它仍然是一个运行时类型转换。



总结:类型转换是一个操作它改变了一个变量的类型(不是的值)。由于变量在PHP中没有类型,它不仅不可能做到,而且是一个毫无意义的事情,首先要问。


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

$obj = (MyClass) $another_class_obj;

解决方案

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.

这篇关于键入用户定义对象的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆