Answers for "php class object"

PHP
1

php object

//create a person object in PHP
$person=new stdClass();
$person->firstName="Chuck";
$person->lastName="Bartowski";
$person->age=27;

print_r($person);
Posted by: Guest on August-06-2019
4

php define object

$x = new stdClass();
Posted by: Guest on February-19-2020
7

create a class in php

<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  function get_name() {
    return $this->name;
  }
  function get_color() {
    return $this->color;
  }
}

$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>
Posted by: Guest on July-22-2020
1

php class

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected properties, but not private
    public $public = 'Public2';
    protected $protected = 'Protected2';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->protected; // Fatal Error
echo $obj2->private; // Undefined
$obj2->printHello(); // Shows Public2, Protected2, Undefined

?>
Posted by: Guest on August-15-2021
0

object php

//object init
  $object = (object) [
    'propertyOne' => 'foo',
    'propertyTwo' => 42,
  ];
Posted by: Guest on June-16-2020
1

php object

$o= new \stdClass();
$o->a = 'new object';

OR

$o = (object) ['a' => 'new object'];
Posted by: Guest on November-20-2020

Browse Popular Code Answers by Language