xxxxxxxxxx
<?php
class Bike
{
function model()
{
$model_name = 'cd100';
echo "bike model:$model_name";
}
}
$obj = new Bike();
$obj->model();
?>
xxxxxxxxxx
$object = new stdClass();
$object->property = 'Here we go';
var_dump($object);
/*
outputs:
object(stdClass)#2 (1) {
["property"]=>
string(10) "Here we go"
}
*/
xxxxxxxxxx
//object init
$object = (object) [
'propertyOne' => 'foo',
'propertyTwo' => 42,
];
xxxxxxxxxx
$o= new \stdClass();
$o->a = 'new object';
OR
$o = (object) ['a' => 'new object'];
xxxxxxxxxx
In PHP8 this has been changed
https://www.php.net/manual/en/migration80.incompatible.php
A number of warnings have been converted into Error exceptions:
Attempting to write to a property of a non-object. Previously this implicitly created an stdClass object for null, false and empty strings.
So if you add properties to a $var, you first need to make it a stdClass()
$var = new stdClass();
$var->propp1 = "nice";
$var->propp2 = 1234;
xxxxxxxxxx
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!
xxxxxxxxxx
<?php
$fruitsArray = array(
"apple" => 20,
"banana" => 30
);
echo $fruitsArray['banana'];
xxxxxxxxxx
//define a class
class MyClass{
//create properties, constructor or methods
}
//create object using "new" keyword
$object = new MyClass();
//or wihtout parenthesis
$object = new MyClass;
xxxxxxxxxx
class MyClass {
public $prop1;
public $prop2;
public function __construct($val1, $val2) {
$this->prop1 = $val1;
$this->prop2 = $val2;
}
public function myMethod() {
return "Hello, world!";
}
}
// Creating an instance of MyClass
$obj = new MyClass('Value 1', 'Value 2');
// Accessing the properties
echo $obj->prop1; // Output: Value 1
echo $obj->prop2; // Output: Value 2
// Calling a method
echo $obj->myMethod(); // Output: Hello, world!