PHP 投射到我的班级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42623498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Cast to my class
提问by SexyMF
why this is not possible:
为什么这是不可能的:
$user = (User) $u[0];
but this is possible
但这是可能的
$bool = (boolean) $res['success'];
I use PHP 7.0.
我使用 PHP 7.0。
回答by Jarlik Stepsto
As I know, in PHP you can only cast to some types:
据我所知,在 PHP 中,您只能转换为某些类型:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(binary) - cast to binary string (PHP 6)
(array) - cast to array
(object) - cast to object
(unset) - cast to NULL (PHP 5)
(see Type Casting)
(参见类型转换)
Instead you could use instanceofto check of specific type:
相反,您可以使用instanceof来检查特定类型:
if($yourvar instanceof YourClass) {
//DO something
} else {
throw new Exception('Var is not of type YourClass');
}
回答by Szabolcs Páll
If you just want to ensure a variable is instance of YourClass and let exception handling to the typesystem you can use the following function:
如果您只想确保变量是 YourClass 的实例并让异常处理到类型系统,您可以使用以下函数:
function implicitFakeCast($myClass): YourClass
{
return $myClass;
}
Note:this will not actually do any casting, rather it throws exceptions in case of class mismatch and lets intellisense treat it as an instance of the target class.
注意:这实际上不会进行任何转换,而是在类不匹配的情况下抛出异常,并让智能感知将其视为目标类的实例。
回答by Ken
For people that do want to be able to cast to a class type. I've found a gist by @borzilleri that uses serialize and unserialize to achieve this: https://gist.github.com/borzilleri/960035.
对于确实希望能够转换为类类型的人。我找到了@borzilleri 的一个要点,它使用序列化和反序列化来实现这一点:https://gist.github.com/borzilleri/960035 。
TL;DR:
特尔;博士:
// make sure to include the namespace when casting
$className = "Some\NameSpace\SomeClassName";
$classNameLength = strlen( $className );
$castedItem = unserialize(
preg_replace(
'/^O:\d+:"[^"]++"/',
"O:$classNameLength:\"$className\"",
serialize( $item )
)
)
回答by Hans Yulian
Objects and primitive types are different. Since it's called as primitive types, they are really simple, maybe only 1 byte, 2 bytes, or 4 bytes, and at most 8 bytes.
对象和原始类型是不同的。既然叫原始类型,其实很简单,可能只有1个字节、2个字节、4个字节,最多8个字节。
When we are talking about object, this object can have different attributes with the others. Then the question from PHP will be is, "is this object really from my Class?" "How to convert this object to my Class?". Thus, you can't parse right away the object using
当我们谈论对象时,这个对象可以与其他对象具有不同的属性。那么来自 PHP 的问题将是,“这个对象真的来自我的类吗?” “如何将此对象转换为我的类?”。因此,您不能立即使用
$myObject = (ClassName) $variable
Then how to cast it? Dunno, but usually the approach is like this:
那怎么投呢?不知道,但通常方法是这样的:
- Create constructor for the class
- In the class, make a method that specifically accept certain parameters, maybe array
- 为类创建构造函数
- 在类中,制作一个专门接受某些参数的方法,可能是数组
here is sample:
这是示例:
public class MyAwesomeClass{
function __construct($thisIsArray){
$this->attributeA = $thisIsArray["A"];
$this->attributeB = $thisIsArray["B"];
......
}
static function fromArray($thisIsArray){
return MyAwesomeClass($thisIsArray);
}
}
$obj = MyAwesomeClass::fromArray($attributes);
回答by Nanne
In addition to the answer on why this is not possible, I would suggest that you write a builder function that creates an object, based on your input. so it would look something like
除了为什么这是不可能的答案之外,我建议您编写一个构建器函数,根据您的输入创建一个对象。所以它看起来像
$user = User::buildFromSomeArrayInput($u[0]);
And then have a builder create a new User
object, assign the right properties, etc. You could just do all this in-place of course, but having a builder function makes sure you won't be doing this on several locations, AND you can set private properties as it is a class-member function. It is a bit more work then having it magically work, but not that much.
The only issue you might have is when you do have a different object that does not expose all the internals you might need. But this is for a reason, as internals might change -> you don't want to rely on that.
然后让构建器创建一个新User
对象,分配正确的属性等。当然,您可以就地完成所有这些操作,但是拥有构建器功能可确保您不会在多个位置执行此操作,并且您可以设置私有属性,因为它是类成员函数。这比让它神奇地工作要多一些工作,但不是那么多。您可能遇到的唯一问题是,当您有一个不同的对象时,该对象不会公开您可能需要的所有内部结构。但这是有原因的,因为内部可能会发生变化-> 您不想依赖它。
There are hacks out there that suggest doing this with serialization. I would suggest to steer away from them, as they are hackish and as far as i'm concerned, not very clear.
有一些黑客建议使用序列化来做到这一点。我建议远离它们,因为它们是骇人听闻的,就我而言,不是很清楚。
回答by sensorario
The reason is that "false" is a string and its true. But false is a boolean.
原因是“false”是一个字符串,它是真的。但 false 是一个布尔值。
$res['success'] = "false"|;
if ($res['success']) { // returns true
// this cose will be executed
}
Another example here: echo "false" == true ? 111 : 222;
that prints 111.
这里的另一个例子:echo "false" == true ? 111 : 222;
打印 111。
And again, ... "42" is a string while 42 is a number.
再一次,......“42”是一个字符串,而 42 是一个数字。
You can always check boolean value of a variable content.
您始终可以检查变量内容的布尔值。
"PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer."
“PHP 不需要(或支持)变量声明中的显式类型定义;变量的类型由使用该变量的上下文决定。也就是说,如果将字符串值赋给变量 $var,则 $var 变为一个字符串。如果然后将一个整数值分配给 $var,它就会变成一个整数。”
Another example from documentation:
文档中的另一个示例:
<?php
$foo = 10; // $foo is an integer
$bar = (boolean) $foo; // $bar is a boolean
?>
Take a look the type comparison tables.
看看类型比较表。
回答by Supun Kavinda
PHP supports two types of casting.
PHP 支持两种类型的转换。
- Implicit Casting
- Explicit Casting
- 隐式转换
- 显式转换
Implicit Casting is done by PHP. For instance, when dividing two integers (5/2), the result will be float (2.5). This conversion is done by PHP.
隐式转换由 PHP 完成。例如,将两个整数 (5/2) 相除时,结果将是浮点数 (2.5)。这种转换是由 PHP 完成的。
Explicit Casting can be by us (programmer). As in your question, you can use () to cast to a new data type. But, everything does not work in this way. Sometimes this can lead to data loss (casting a float (2.52) to an integer will drop the decimal value which can be useful). Casting to objects can be risky, as different objects behave in different ways.
显式转换可以由我们(程序员)进行。正如您的问题,您可以使用 () 转换为新的数据类型。但是,一切都不会以这种方式工作。有时这会导致数据丢失(将浮点数 (2.52) 转换为整数会丢弃有用的十进制值)。投射到对象可能有风险,因为不同的对象有不同的行为方式。
So, if you are thinking of casting to an object, use an object constructor.
因此,如果您正在考虑强制转换为对象,请使用对象构造函数。
$user = new User($u[0]);
The user class should be something like this.
用户类应该是这样的。
class User {
public function __construct($user) {
$this -> user = $user;
}
}
In this way, you can create your own object to manipulate user-related data and more.
通过这种方式,您可以创建自己的对象来操作与用户相关的数据等。