0% found this document useful (0 votes)
83 views

Search: PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

Uploaded by

perexwi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

Search: PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

Uploaded by

perexwi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

Downloads
Documentation
Get Involved
Help

Search
PHPKonf: Istanbul PHP Conference 2017
Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Errors
Exceptions
Generators
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers
Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Magic Quotes
Hiding PHP
Keeping Current
1 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Safe Mode
Command line usage
Garbage Collection
DTrace Dynamic Tracing
Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Credit Card Processing
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
GUI Extensions
Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
gp
2 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

Previous man page


gn
Next man page
G
Scroll to bottom
gg
Scroll to top
gh
Goto homepage
gs
Goto search
(current page)
/
Focus search box
Recursos
Arrays
Manual de PHP
Referencia del lenguaje
Tipos
Change language:

Spanish

Edit Report a Bug

Objetos
Inicializacin de objetos
Para crear un nuevo object, utilice la sentencia new para instanciar una
clase:
<?php
classfoo
{
functionhacer_algo()
{
echo"Haciendoalgo.";
}
}
$bar=newfoo;
$bar->hacer_algo();
?>

Para una descripcin completa, vase el captulo Clases y objetos.

Conversin a un objeto
3 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

Si un object se convierte en un object, ste no se modifica. Si un valor de


cualquier otro tipo se convierte en un object, se crea una nueva instancia de
la clase stdClass incorporada. Si el valor es NULL, la nueva instancia estar
vaca. Un array se convierte en un object con las propiedades nombradas
como claves y los valores correspondientes, con la excepcin de las claves
numricas, las cuales sern inaccesibles a menos que sean recorridas.
<?php
$obj=(object)array('1'=>'foo');
var_dump(isset($obj->{'1'}));//muestra'bool(false)'
var_dump(key($obj));//muestra'int(1)'
?>

Para cualquier otro valor, una variable miembro llamada scalar contendr el
valor.
<?php
$obj=(object)'ciao';
echo$obj->scalar;//muestra'ciao'
?>

add a note

User Contributed Notes 22 notes


up
down
218
helpful at stranger dot com
5 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
down
53
Anthony
11 months 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) {}

4 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

?>
$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
down
20
twitter/matt2000
1 year 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
down
35
Ashley Dambra
2 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:

5 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

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};
};
}
}

6 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

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

up
down
14
qeremy [atta] gmail [dotta] com
4 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!
?>

7 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

up
down
15
Mithras
8 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;
}
?>

up
down
12
gabe at fijiwebdesign dot com
9 years ago
In response to sirbinam.
You cannot call a function or method before it exists. In your example, the global
instance of stdout is just being passed around to differnet references (pointers). It
however exists in the "dump" function scope via the global keyword.
The code below works fine and illustrates that "stdout" has been defined before its
instantiation.
<?php
class profiler{
function profiler(){
$this->starttime = microtime();
}
function dump(){
global $stdout;
$this->endtime = microtime();
$duration = $this->endtime - $this->starttime;
$stdout->write($duration);
}
}
class stdout{
function write($msg){
echo $msg;
}
}

8 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

$stdout =& new stdout();


$profiler =& new profiler();
$profiler->dump();
?>
All classes and functions declarations within a scope exist even before the php
execution reaches them. It does not matter if you have your classes defined on the
first or last line, as long as they are in the same scope as where they are called and
are not in a conditional statement that has not been evaluated yet.

up
down
7
cFreed at orange dot fr
7 years ago
CAUTION:
"Arrays convert to an object with properties named by keys, and corresponding values".
This is ALWAYS true, which means that even numeric keys are accepted when converting.
But the resulting properties cannot be accessed, since they don't match the variables
naming rules.
So this:
<?php
$x = (object) array('a'=>'A', 'b'=>'B', 'C');
echo '<pre>'.print_r($x, true).'</pre>';
?>
works and displays:
stdClass Object
(
[a] => A
[b] => B
[0] => C
)
But this:
<?php
echo '<br />'.$x->a;
echo '<br />'.$x->b;
echo '<br />'.$x->{0}; # (don't use $x->0, which is obviously a syntax error)
?>
fails and displays:
A
B
Notice: Undefined property: stdClass::$0 in...

up
down
6
mailto dot aurelian at gmail dot com
7 years ago

9 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

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
down
0
Cosmitar: mhherrera31 at hotmail
6 years ago
i would like to share a curious behavior on casted objects. Casting an object from a
class with private/protected attributes results a stdClass with a private/protected
attribute for get.
Example:
<?PHP
class Foo{
private $priv = 1;
public $pub = 2;
public function getSimple(){
return (object)(array) $this; //the array cast is to force a stdClass result
}
}
$bar = new Foo();
var_dump($bar->getSimple();// output: object(stdClass)#3 (2) { ["priv:private"]=>
int(1) ["pub"]=> int(2) }
var_dump($bar->getSimple()->priv);// output: NULL, not a Fatal Error
var_dump($bar->getSimple()->pub);// output: int(2)
$barSimple = $bar->getSimple();
$barSimple->priv = 10;
var_dump($barSimple->priv);// output: int(10)
?>

up
down
-1
info at keltoi-web dot com
13 years ago
PHP supports recursive type definitions as far as I've tried. The class below (a _very_
simple tree) is an example:
class Tree {

10 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

up
down
-2
wyattstorch42 at outlook dot com
3 years ago

11 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

up
down
-2
mortoray at ecircle-ag dot com
11 years ago

12 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

up
down
-4
Anonymous
7 years ago

13 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

up
down
-8
spidgorny at gmail dot com
7 years ago
If having

14 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

up
down
-7
Trevor Blackbird > yurab.com
11 years ago

up

15 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

down
-4
developer dot amankr at gmail dot com (Aman Kuma)
10 months ago

up
down
-2
solly dot ucko at google dot com
8 months ago
To create an object with values, in javascript you would use `{key: value}`. In PHP you
use `[key=>value]`.

up
down
-9
ludvig dot ericson at gmail dot com
10 years ago
In reply to the usort thing, you can access a property of an object dynamically by:
<?php

16 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

up
down
-10
iblun at gmx dot net
11 years ago

up
down
-15
Isaac Z. Schlueter i at foohack dot com
8 years ago

17 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

up
down
-12
Ashley Dambra
2 years ago

add a note

Tipos
Introduccin
Booleanos
Nmeros enteros (Integers)
Nmeros de punto flotante
Cadenas de caracteres (Strings)
Arrays
Objetos
Recursos
NULO

18 de 19

14/01/17 13:30

PHP: Objetos - Manual

http://php.net/manual/es/language.types.object.php

Llamadas de retorno (Callbacks / Callables)


Seudotipos y variables usadas en esta documentacin
Manipulacin de tipos
Copyright 2001-2017 The PHP Group
My PHP.net
Contact
Other PHP.net sites
Mirror sites
Privacy policy

19 de 19

14/01/17 13:30

You might also like