有没有办法将数组转换为类属性?

[英]Is there any way to convert an array to class properties?


There is a way to get class properties and convert it using (array) casting.

有一种方法可以获取类属性并使用(数组)转换来转换它。

$user = (array) get_object_vars($userObject)

But I wonder, I didn't find any direct method to convert array to class properties.

但我想知道,我没有找到任何直接的方法来将数组转换为类属性。

Suppose I have user class with following implementation:

假设我有以下实现的用户类:

class User
{
    private $id = 0;
    private $fname = '';
    private $lname = '';
    private $username = '';
}

I have following array:

我有以下数组:

$user = array(
    'id'=> 2,
    'fname' => 'FirstName',
    'lname' => 'LastName',
    'username' => 'UserName'
);

I am looking for a type cast just like we have (object). The issue is (object) type cast converts array to stdClass object, but here I want my array to be converted in to my specified class.

我正在寻找一个像我们(对象)一样的类型转换。问题是(对象)类型转换将数组转换为stdClass对象,但在这里我希望我的数组转换为我指定的类。

The example should be stated like: (my assumption, that PHP should have this. Or it may already have some thing like this and I dont know.)

这个例子应该表达如下:(我的假设,PHP应该有这个。或者它可能已经有这样的东西,我不知道。)

$userobj = (object User) $user;

And the result of above syntax should be just like:

上面语法的结果应该是这样的:

$userobj->id = $user['id'];
$userobj->fname = $user['fname'];
$userobj->lname = $user['lname'];
$userobj->username = $user['username'];

I want to know if there any direct method, not a logic of mapping. Looking for language level trick.

我想知道是否有任何直接方法,而不是映射逻辑。寻找语言级技巧。

Note: I am aware of the use of foreach to get above done. I am looking for some direct method if available in PHP but not get into focus yet (may be!).

注意:我知道使用foreach来完成上述工作。我正在寻找一些直接的方法,如果在PHP中可用但尚未成为焦点(可能是!)。

Following doesn't solve my question: Convert/cast an stdClass object to another class

以下内容无法解决我的问题:将stdClass对象转换/转换为另一个类

2 个解决方案

#1


1  

An array is not an object. So you can't cast it with a language construct. Even casting user defined objects in PHP is not possible.

数组不是对象。所以你不能用语言结构来构建它。甚至无法在PHP中构建用户定义的对象。

So you have to write your own logic. There are some fancy approaches by serialize() the object, change the class name and unserialize() it again to automate the process.

所以你必须编写自己的逻辑。 serialize()对象有一些奇特的方法,更改类名并再次反序列化()以自动化该过程。

Also you could write a cast function using reflection. But everything needs user logic.

您也可以使用反射编写强制转换函数。但一切都需要用户逻辑。

See also this post on SO: Type casting for user defined objects

另请参阅SO上的这篇文章:为用户定义的对象输入类型

So if you really like to cast objects I ended up with this function (see it in action):

因此,如果您真的想要投射对象,我最终会使用此功能(请参阅其中的操作):

function cast($to, $obj)
{
    $toLength = strlen($to);
    $serializedObj = preg_replace('/^O:\\d+:"[^"]+"/', 'O:' . $toLength . ':"' . $to . '"', serialize($obj));

    $serializedObj = preg_replace_callback('/s:(\\d+):"([^"]+)";(.+?);/', function($m) use($to, $toLength) {
        $propertyName = $m[2];
        $propertyLength = $m[1];

        if(strpos($m[2], "\0*\0") === false && ($pos = strrpos($m[2], "\0")) !== false) {
            $propertyName = "\0" . $to . "\0" . substr($m[2], $pos + 1);
            $propertyLength = ($m[1] + $toLength - $pos + 1);
        }

        return 's:' . $propertyLength . ':"' . $propertyName . '";' . $m[3] . ';';
    }, $serializedObj);

    return unserialize($serializedObj);
}

$user = array(
    'id'=> 2,
    'fname' => 'FirstName',
    'lname' => 'LastName',
    'username' => 'UserName'
);

$userObj = cast(User::class, (object)$user);

print_r($userObj);

But I would never ever use this function in production. It's just an experimental thing.

但我永远不会在生产中使用这个功能。这只是一个实验性的事情。

Update

Okay I rethought how casting is handled in Java. In Java you actually can just cast from an object to a child object of it. You can't cast from any object to any other.

好吧,我重新思考如何在Java中处理转换。在Java中,您实际上只能从一个对象转换为它的子对象。您无法从任何对象转换为任何其他对象。

So you could do this in Java:

所以你可以用Java做到这一点:

$apple = new Apple();
$macintoshApple = (MacintoshApple)$apple;

given that MacintoshApple extends Apple.

鉴于MacintoshApple扩展了Apple。

But you can't cast two unrelated objects like:

但你不能投两个不相关的对象,如:

$apple = new Apple();
$pear = (Pear)$apple;

#2


0  

Based on your response to comment by @AbraCadaver I would look at using something like this to load DB results into an instantiated class of your choice:

根据您对@AbraCadaver评论的回应,我会考虑使用类似的东西将DB结果加载到您选择的实例化类中:

// using MySQLi
$mysqli_result = ...; // your mysqli_result object
while($class_obj = $mysqli_result->fetch_object('your_class_name')) {
    // do something
}

// using PDO
$pdo_statement = ...; // your PDOStatement object
while($class_obj = $pdo_statement->fetch_object('your_class_name')) {
    // do something
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/05/20/a9d80a9248464f94d5848ada8e5241ed.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号