For real quick and dirty one-liner anonymous objects, just cast an associative array:
<?php
$obj = (object) array('foo' => 'bar', 'property' => 'value');
echo $obj->foo; // prints 'bar'
echo $obj->property; // prints 'value'
?>
... no need to create a new class or function to accomplish it.
Classi e Oggetti
Indice dei contenuti
- Introduzione
- Nozioni di base
- Properties
- Costanti di classe
- Caricamento automatico delle classi
- Constructors and Destructors
- Visibility
- Object Inheritance
- Scope Resolution Operator (::)
- Static Keyword
- Astrazione delle classi
- Object Interfaces
- Traits
- Overloading
- Object Iteration
- Magic Methods
- Final Keyword
- Clonazione di oggetti
- Comparing Objects
- Type Hinting
- Late Static Bindings
- Objects and references
- Object Serialization
- OOP Changelog
Jason ¶
4 years ago
farzan at ifarzan dot com ¶
8 years ago
PHP 5 is very very flexible in accessing member variables and member functions. These access methods maybe look unusual and unnecessary at first glance; but they are very useful sometimes; specially when you work with SimpleXML classes and objects. I have posted a similar comment in SimpleXML function reference section, but this one is more comprehensive.
I use the following class as reference for all examples:
<?php
class Foo {
public $aMemberVar = 'aMemberVar Member Variable';
public $aFuncName = 'aMemberFunc';
function aMemberFunc() {
print 'Inside `aMemberFunc()`';
}
}
$foo = new Foo;
?>
You can access member variables in an object using another variable as name:
<?php
$element = 'aMemberVar';
print $foo->$element; // prints "aMemberVar Member Variable"
?>
or use functions:
<?php
function getVarName()
{ return 'aMemberVar'; }
print $foo->{getVarName()}; // prints "aMemberVar Member Variable"
?>
Important Note: You must surround function name with { and } or PHP would think you are calling a member function of object "foo".
you can use a constant or literal as well:
<?php
define(MY_CONSTANT, 'aMemberVar');
print $foo->{MY_CONSTANT}; // Prints "aMemberVar Member Variable"
print $foo->{'aMemberVar'}; // Prints "aMemberVar Member Variable"
?>
You can use members of other objects as well:
<?php
print $foo->{$otherObj->var};
print $foo->{$otherObj->func()};
?>
You can use mathods above to access member functions as well:
<?php
print $foo->{'aMemberFunc'}(); // Prints "Inside `aMemberFunc()`"
print $foo->{$foo->aFuncName}(); // Prints "Inside `aMemberFunc()`"
?>
corpus-deus at softhome dot net ¶
2 years ago
With regards to Singleton patterns (and variable class names) - try:
<?php
class MyClass {
// singleton instance
private static $instance;
// private constructor function
// to prevent external instantiation
private __construct() { }
// getInstance method
public static function getInstance() {
if(!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
//...
}
?>
redrik at gmail dot com ¶
4 years ago
Maybe someone will find these classes, which simulate enumeration, useful.
<?php
class Enum {
protected $self = array();
public function __construct( /*...*/ ) {
$args = func_get_args();
for( $i=0, $n=count($args); $i<$n; $i++ )
$this->add($args[$i]);
}
public function __get( /*string*/ $name = null ) {
return $this->self[$name];
}
public function add( /*string*/ $name = null, /*int*/ $enum = null ) {
if( isset($enum) )
$this->self[$name] = $enum;
else
$this->self[$name] = end($this->self) + 1;
}
}
class DefinedEnum extends Enum {
public function __construct( /*array*/ $itms ) {
foreach( $itms as $name => $enum )
$this->add($name, $enum);
}
}
class FlagsEnum extends Enum {
public function __construct( /*...*/ ) {
$args = func_get_args();
for( $i=0, $n=count($args), $f=0x1; $i<$n; $i++, $f *= 0x2 )
$this->add($args[$i], $f);
}
}
?>
Example usage:
<?php
$eFruits = new Enum("APPLE", "ORANGE", "PEACH");
echo $eFruits->APPLE . ",";
echo $eFruits->ORANGE . ",";
echo $eFruits->PEACH . "\n";
$eBeers = new DefinedEnum("GUINESS" => 25, "MIRROR_POND" => 49);
echo $eBeers->GUINESS . ",";
echo $eBeers->MIRROR_POND . "\n";
$eFlags = new FlagsEnum("HAS_ADMIN", "HAS_SUPER", "HAS_POWER", "HAS_GUEST");
echo $eFlags->HAS_ADMIN . ",";
echo $eFlags->HAS_SUPER . ",";
echo $eFlags->HAS_POWER . ",";
echo $eFlags->HAS_GUEST . "\n";
?>
Will output:
1, 2, 3
25, 49
1,2,4,8 (or 1, 10, 100, 1000 in binary)
midir ¶
4 years ago
There are a couple of tricks you can do with PHP's classes that programmers from C++, etc., will find very peculiar, but which can be useful.
You can create instances of classes without knowing the class name in advance, when it's in a variable:
<?php
$type = 'cc';
$obj = new $type; // outputs "hi!"
class cc {
function __construct() {
echo 'hi!';
}
}
?>
You can also conditionally define them by wrapping them in if/else blocks etc, like so:
<?php
if (expr) {
class cc {
// version 1
}
} else {
class cc {
// version 2
}
}
?>
It makes up for PHP's lack of preprocessor directives. The caveat is that the if/else code body must have been executed before you can use the class, so you need to pay attention to the order of the code, and not use things before they're defined.
dances_with_peons at live dot com ¶
2 years ago
As of PHP 5.3, $className::funcName() works fine.
<?php
class test
{
public static function run() { print "Works\n"; }
}
$className = 'test';
$className::run();
?>
on my system, prints "Works". May work with earlier versions of PHP as well. Even if it doesn't, there's always
<?php
$className = 'test';
call_user_func(array($className, 'run'));
?>
The point is, there's no need for eval.
dances_with_peons at live dot com ¶
2 years ago
As of PHP 5.3, $className::funcName() works fine.
<?php
class test
{
public static function run() { print "Works\n"; }
}
$className = 'test';
$className::run();
?>
on my system, prints "Works". It may work with earlier versions of PHP as well.
meetyashah at gmail dot com ¶
9 days ago
class Pizza
{
private $firstName;
private $lastName;
private $address;
private $city;
private $postalcode;
private $telephone;
private $email;
public function input(){
$this->firstName = ($_POST['firstName']);
$this->lastName = ($_POST['lastName']);
$this->address = ($_POST['address']);
$this->city = ($_POST['city']);
$this->postalCode = ($_POST['postalcode']);
$this->telephone = ($_POST['telephone']);
$this->email = ($_POST['email']);
}
public function show() {
echo 'firstName: '.$this->firstName;
echo 'lastName: '.$this->lastName;
echo 'address: '.$this->address;
echo 'city: '.$this->city;
echo 'postalCode'.$this->postalCode;
echo 'telephone'.$this->telephone;
echo 'email: '.$this->email;
}
}
in the body of the html page :
<?php
$pizzaInstance1 = new Pizza;
$pizzaInstance1->input();
$pizzaInstance1->show();
?>
