ΠžΠ±ΡŠΠ΅ΠΊΡ‚Ρ‹

Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°

НовыС ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Ρ‹ ΡΠΎΠ·Π΄Π°ΡŽΡ‚ Π²Ρ‹Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ΠΌ new, ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ создаёт Π² ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΠΎΠΉ экзСмпляр класса:

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #1 Π‘ΠΎΠ·Π΄Π°Π½ΠΈΠ΅ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°

<?php

class foo
{
function
do_foo()
{
echo
"Код foo.";
}
}

$bar = new foo();
$bar->do_foo();

?>

ПолноС рассмотрСниС ΠΏΡ€ΠΎΠΈΠ·Π²ΠΎΠ΄ΠΈΡ‚ Ρ€Π°Π·Π΄Π΅Π» Β«ΠšΠ»Π°ΡΡΡ‹ ΠΈ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Ρ‹Β».

ΠŸΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠ΅ Π² ΠΎΠ±ΡŠΠ΅ΠΊΡ‚

ΠŸΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠ΅ Ρ‚ΠΈΠΏΠ° object Π² Ρ‚ΠΈΠΏ object Π½Π΅ ΠΈΠ·ΠΌΠ΅Π½ΠΈΡ‚ Ρ‚ΠΈΠΏ значСния. ΠžΠ±ΡŠΠ΅ΠΊΡ‚ Π½Π΅ измСнится ΠΏΡ€ΠΈ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠΈ значСния с Ρ‚ΠΈΠΏΠΎΠΌ object Π² Ρ‚ΠΈΠΏ object. ΠŸΡ€ΠΈ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠΈ значСния Π΄Ρ€ΡƒΠ³ΠΎΠ³ΠΎ Ρ‚ΠΈΠΏΠ° Π² object PHP создаёт Π½ΠΎΠ²Ρ‹ΠΉ экзСмпляр встроСнного класса stdClass. Новый экзСмпляр Π±ΡƒΠ΄Π΅Ρ‚ пустым, Ссли Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ Ρ€Π°Π²Π½ΡΠ»ΠΎΡΡŒ null. ΠœΠ°ΡΡΠΈΠ²Ρ‹ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Ρ‹Π²Π°ΡŽΡ‚ΡΡ Π² Ρ‚ΠΈΠΏ object с ΠΈΠΌΠ΅Π½Π°ΠΌΠΈ ΠΏΠΎΠ»Π΅ΠΉ ΠΊΠ°ΠΊ Ρƒ ΠΊΠ»ΡŽΡ‡Π΅ΠΉ массива ΠΈ Ρ‚Π΅ΠΌΠΈ ΠΆΠ΅ значСниями. ΠžΠ±Ρ€Π°Ρ‚ΠΈΡ‚Π΅ Π²Π½ΠΈΠΌΠ°Π½ΠΈΠ΅, Ρ‡Ρ‚ΠΎ Π΄ΠΎ PHP 7.2.0 ΠΏΡ€ΠΈ Ρ‚Π°ΠΊΠΎΠΌ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠΈ доступ ΠΊ числовым ΠΊΠ»ΡŽΡ‡Π°ΠΌ появляСтся Ρ‚ΠΎΠ»ΡŒΠΊΠΎ ΠΏΡ€ΠΈ ΠΈΡ‚Π΅Ρ€Π°Ρ†ΠΈΠΈ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°.

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #2 ΠŸΡ€ΠΈΠ²Π΅Π΄Π΅Π½ΠΈΠ΅ ΠΊ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Ρƒ

<?php

$obj
= (object) array('1' => 'foo');

var_dump(isset($obj->{'1'})); // Π’Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ 'bool(true)'

// Начиная с PHP 8.1 Π²Ρ‹Π·ΠΎΠ² Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ key() Π½Π° ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°Ρ… устарСл
var_dump(key($obj)); // Π’Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ 'string(1) "1"'

?>

ΠžΡΡ‚Π°Π»ΡŒΠ½Ρ‹Π΅ значСния ΠΏΡ€ΠΈ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠΈ PHP помСстит Π² ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΡƒΡŽ-Ρ‡Π»Π΅Π½ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° с Π½Π°Π·Π²Π°Π½ΠΈΠ΅ΠΌ scalar с исходным Ρ‚ΠΈΠΏΠΎΠΌ значСния.

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #3 ΠŸΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠ΅ Π² ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ Ρ‡Π΅Ρ€Π΅Π· ΠΏΡ€ΠΈΠ²Π΅Π΄Π΅Π½ΠΈΠ΅ Ρ‚ΠΈΠΏΠ° (object)

<?php

$obj
= (object) 'ΠŸΡ€ΠΈΠ²Π΅Ρ‚';
echo
$obj->scalar; // Π’Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ 'ΠŸΡ€ΠΈΠ²Π΅Ρ‚'

?>
οΌ‹Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΡ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ 8 notes

up
699
helpful at stranger dot com ΒΆ
14 years ago
By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose:

<?php $genericObject = new stdClass(); ?>

I had the most difficult time finding this, hopefully it will help someone else!
up
237
Anthony ΒΆ
10 years ago
In PHP 7 there are a few ways to create an empty object:

<?php
$obj1 = new \stdClass; // Instantiate stdClass object
$obj2 = new class{}; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object

var_dump($obj1); // object(stdClass)#1 (0) {}
var_dump($obj2); // object(class@anonymous)#2 (0) {}
var_dump($obj3); // object(stdClass)#3 (0) {}
?>

$obj1 and $obj3 are the same type, but $obj1 !== $obj3. Also, all three will json_encode() to a simple JS object {}:

<?php
echo json_encode([
    new \stdClass,
    new class{},
    (object)[],
]);
?>

Outputs: [{},{},{}]
up
49
Ashley Dambra ΒΆ
12 years ago
Here a new updated version of 'stdObject' class. It's very useful when extends to controller on MVC design pattern, user can create it's own class.

Hope it help you.

 <?php
class stdObject {
    public function __construct(array $arguments = array()) {
        if (!empty($arguments)) {
            foreach ($arguments as $property => $argument) {
                $this->{$property} = $argument;
            }
        }
    }

    public function __call($method, $arguments) {
        $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}

// Usage.

$obj = new stdObject();
$obj->name = "Nick";
$obj->surname = "Doe";
$obj->age = 20;
$obj->adresse = null;

$obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject).
    echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse;
};

$func = "setAge";
$obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method.
    $stdObject->age = $age;
};

$obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'.

// Create dynamic method. Here i'm generating getter and setter dynimically
// Beware: Method name are case sensitive.
foreach ($obj as $func_name => $value) {
    if (!$value instanceOf Closure) {

        $obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.
            $stdObject->{$func_name} = $value;
        };

        $obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.
            return $stdObject->{$func_name};
        };

    }
}

$obj->setName("John");
$obj->setAdresse("Boston");

$obj->getInfo();
?>
up
38
twitter/matt2000 ΒΆ
11 years ago
As of PHP 5.4, we can create stdClass objects with some properties and values using the more beautiful form:

<?php
  $object = (object) [
    'propertyOne' => 'foo',
    'propertyTwo' => 42,
  ];
?>
up
13
developer dot amankr at gmail dot com (Aman Kuma) ΒΆ
10 years ago
<!--Example shows how to convert array to stdClass Object and how to access its value for display -->
<?php 
$num = array("Garha","sitamarhi","canada","patna"); //create an array
$obj = (object)$num; //change array to stdClass object 

echo "<pre>";
print_r($obj); //stdClass Object created by casting of array 

$newobj = new stdClass();//create a new 
$newobj->name = "India";
$newobj->work = "Development";
$newobj->address="patna";

$new = (array)$newobj;//convert stdClass to array
echo "<pre>";
print_r($new); //print new object

##How deals with Associative Array

$test = [Details=>['name','roll number','college','mobile'],values=>['Naman Kumar','100790310868','Pune college','9988707202']];
$val = json_decode(json_encode($test),false);//convert array into stdClass object

echo "<pre>";
print_r($val);

echo ((is_array($val) == true ?  1 : 0 ) == 1 ? "array" : "not an array" )."</br>"; // check whether it is array or not
echo ((is_object($val) == true ?  1 : 0 ) == 1 ? "object" : "not an object" );//check whether it is object or not 
?>
up
4
qeremy [atta] gmail [dotta] com ΒΆ
14 years ago
Do you remember some JavaScript implementations?

// var timestamp = (new Date).getTime();

Now it's possible with PHP 5.4.*;

<?php
class Foo
{
    public $a = "I'm a!";
    public $b = "I'm b!";
    public $c;
    
    public function getB() {
        return $this->b;
    }
    
    public function setC($c) {
        $this->c = $c;
        return $this;
    }
    
    public function getC() {
        return $this->c;
    }
}

print (new Foo)->a;      // I'm a!
print (new Foo)->getB(); // I'm b!
?>

or

<?php
// $_GET["c"] = "I'm c!";
print (new Foo)
       ->setC($_GET["c"])
       ->getC(); // I'm c!
?>
up
5
mailto dot aurelian at gmail dot com ΒΆ
16 years ago
You can create [recursive] objects with something like:
<?php
  $literalObjectDeclared = (object) array(
     'foo' => (object) array(
          'bar' => 'baz',
          'pax' => 'vax'
      ),
      'moo' => 'ui'
   );
print $literalObjectDeclared->foo->bar; // outputs "baz"!
?>
up
-4
Mithras ΒΆ
17 years ago
In response to harmor: if an array contains another array as a value, you can recursively convert all arrays with:

<?php
function arrayToObject( $array ){
  foreach( $array as $key => $value ){
    if( is_array( $value ) ) $array[ $key ] = arrayToObject( $value );
  }
  return (object) $array;
}
?>