PHP.mk документација

Објекти

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

language.types.object.php PHP.net прокси Преводот е вчитан
Оригинал на PHP.net
Патека language.types.object.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + преведен приказ Кодовите, табелите и белешките остануваат читливи во истиот тек.
Објекти

Референца за `language.types.object.php` со подобрена типографија и навигација.

language.types.object.php

Објекти

Иницијализација на објект

За да креирате нов object, користете го new изразот за инстанцирање класа:

Пример #1 Конструкција на објект

<?php
class foo
{
function
do_foo()
{
echo
"Doing foo.";
}
}

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

За целосна дискусија, видете го Класи и објекти chapter.

Конвертирање во објект

Ако еден object се претвори во object, не се менува. Ако вредност од кој било друг тип се претвори во object, нова инстанца на stdClass вградена класа е креирана. Ако вредноста беше null, новата инстанца ќе биде празна. Еден array се претвора во object со својства именувани по клучеви и соодветни вредности. Забележете дека во овој случај пред PHP 7.2.0 нумеричките клучеви биле недостапни освен ако не се итерираат.

Пример #2 Претворање во објект

<?php
$obj
= (object) array('1' => 'foo');
var_dump(isset($obj->{'1'})); // outputs 'bool(true)'

// Deprecated as of PHP 8.1
var_dump(key($obj)); // outputs 'string(1) "1"'
?>

За било која друга вредност, член променлива именувана scalar ќе ја содржи вредноста.

Пример #3 (object) cast

<?php
$obj
= (object) 'ciao';
echo
$obj->scalar; // outputs 'ciao'
?>

Белешки од корисници 8 белешки

корисно на stranger dot com
пред 14 години
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!
Ентони
пред 10 години
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: [{},{},{}]
twitter/matt2000
пред 10 години
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,
  ];
?>
Ешли Дамбра
12 години пред
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();
?>
developer dot amankr at gmail dot com (Аман Кума)
пред 10 години
<!--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 
?>
qeremy [на] gmail [точка] com
пред 14 години
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!
?>
mailto точка aurelian на gmail точка com
пред 16 години
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"!
?>
Митрaс
пред 17 години
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;
}
?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.