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

Основи

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

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

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

language.oop5.basic.php

Основи

class

Основните дефиниции на класа започнуваат со клучниот збор class, проследено со име на класа, проследено со пар загради кои ги опфаќаат дефинициите на својствата и методите што припаѓаат на класата.

Името на класата може да биде кој било валиден етикета, под услов да не е PHP резервиран збор. Од PHP 8.4.0, користењето на една подвлечена црта _ како име на класа е застарено. Валидно име на класа започнува со буква или подвлечена црта, проследено со кој било број букви, броеви или подвлечени црти. Како регуларен израз, тоа би било изразено вака: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$.

Класата може да содржи свои constants, variables (наречени „својства“), и функции (наречени „методи“).

Пример #1 Едноставна дефиниција на класа

<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';

// method declaration
public function displayVar() {
echo
$this->var;
}
}
?>

Псевдо-променливата $this е достапно кога метод се повикува од контекст на објект. $this е вредноста на повикувачкиот објект.

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Повикувањето на нестатичен метод статички фрла Грешка. Пред PHP 8.0.0, ова би генерирало известување за застареност, и $this ќе биде недефинирано.

Пример #2 Некои примери на $this pseudo-variable

<?php
class A
{
function
foo()
{
if (isset(
$this)) {
echo
'$this is defined (';
echo
get_class($this);
echo
")\n";
} else {
echo
"\$this is not defined.\n";
}
}
}

class
B
{
function
bar()
{
A::foo();
}
}

$a = new A();
$a->foo();

A::foo();

$b = new B();
$b->bar();

B::bar();
?>

Излез од горниот пример во PHP 7:

$this is defined (A)

Deprecated: Non-static method A::foo() should not be called statically in %s  on line 27
$this is not defined.

Deprecated: Non-static method A::foo() should not be called statically in %s  on line 20
$this is not defined.

Deprecated: Non-static method B::bar() should not be called statically in %s  on line 32

Deprecated: Non-static method A::foo() should not be called statically in %s  on line 20
$this is not defined.

Излез од горниот пример во PHP 8:

$this is defined (A)

Fatal error: Uncaught Error: Non-static method A::foo() cannot be called statically in %s :27
Stack trace:
#0 {main}
  thrown in %s  on line 27

Класи само за читање

Од PHP 8.2.0, класата може да биде означена со readonly модификатор. Означувањето на класа како readonly ќе ги додаде readonly modifier на секое декларирано својство и ќе спречи создавање на динамични својства. Покрај тоа, невозможно е да се додаде поддршка за нив со користење на AllowDynamicProperties атрибутот. Обидот да се направи тоа ќе предизвика грешка при компајлирање.

<?php
#[\AllowDynamicProperties]
readonly class
Foo {
}

// Fatal error: Cannot apply #[AllowDynamicProperties] to readonly class Foo
?>

Бидејќи ниту непроменетите ниту статичните својства не можат да бидат означени со readonly модификаторот, ниту readonly класите можат да ги декларираат:

<?php
readonly class Foo
{
public
$bar;
}

// Fatal error: Readonly property Foo::$bar must have type
?>
<?php
readonly class Foo
{
public static
int $bar;
}

// Fatal error: Readonly class Foo cannot declare static properties
?>

А readonly класата може да биде extended ако и само ако, дете класата е исто така readonly class.

new

За да се создаде инстанца на класа, new клучниот збор мора да се користи. Објект секогаш ќе биде создаден освен ако објектот има constructor дефинирано што фрла exception при грешка. Класите треба да бидат дефинирани пред инстанцирање (а во некои случаи ова е потребно).

Ако променлива што содржи string со името на класата се користи со new, нова инстанца на таа класа ќе биде создадена. Ако класата е во именски простор, нејзиното целосно квалификувано име мора да се користи кога се прави ова.

Забелешка:

Ако нема аргументи што треба да се поминат на конструкторот на класата, заградите по името на класата може да се изостават.

Пример #3 Создавање инстанца

<?php
class SimpleClass {
}

$instance = new SimpleClass();
var_dump($instance);

// This can also be done with a variable:
$className = 'SimpleClass';
$instance = new $className(); // new SimpleClass()
var_dump($instance);
?>

Од PHP 8.0.0, користењето на new со произволни изрази е поддржано. Ова овозможува посложено инстанцирање ако изразот произведува string. Изразите мора да бидат завиткани во загради.

Пример #4 Создавање инстанца користејќи произволен израз

Во дадениот пример покажуваме повеќе примери на валидни произволни изрази кои произведуваат име на класа. Ова покажува повик до функција, конкатенација на низи и ::class constant.

<?php

class ClassA extends \stdClass {}
class
ClassB extends \stdClass {}
class
ClassC extends ClassB {}
class
ClassD extends ClassA {}

function
getSomeClass(): string
{
return
'ClassA';
}

var_dump(new (getSomeClass()));
var_dump(new ('Class' . 'B'));
var_dump(new ('Class' . 'C'));
var_dump(new (ClassD::class));
?>

Излез од горниот пример во PHP 8:

object(ClassA)#1 (0) {
}
object(ClassB)#1 (0) {
}
object(ClassC)#1 (0) {
}
object(ClassD)#1 (0) {
}

Во контекст на класа, можно е да се создаде нов објект со new self and new parent.

Во контекст на класа, можно е да се создаде нов објект со cloning it.

Кога веќе создадена инстанца на класа ќе се додели на нова променлива, новата променлива ќе пристапи до истата инстанца како објектот што беше доделен. Ова однесување е исто и при поминување на инстанци на функција. Копија од веќе создаден објект може да се направи со

<?php
class SimpleClass {
public
string $var;
}

$instance = new SimpleClass();

$assigned = $instance;
$reference =& $instance;

$instance->var = '$assigned will have this value';

$instance = null; // $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

Пример #5 Доделување објект

Можно е да се создадат инстанци на објект на неколку начини:

<?php

class Test
{
public static function
getNew()
{
return new static();
}
}

class
Child extends Test {}

$obj1 = new Test(); // By the class name
$obj2 = new $obj1(); // Through the variable containing an object
var_dump($obj1 !== $obj2);

$obj3 = Test::getNew(); // By the class method
var_dump($obj3 instanceof Test);

$obj4 = Child::getNew(); // Through a child class method
var_dump($obj4 instanceof Child);

?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

bool(true)
bool(true)
bool(true)

Пример #6 Создавање нови објекти

Можно е да се пристапи член на новосоздаден објект во еден израз:

<?php
echo (new DateTime())->format('Y'), PHP_EOL;

// surrounding parentheses are optional as of PHP 8.4.0
echo new DateTime()->format('Y'), PHP_EOL;
?>

Горниот пример ќе прикаже нешто слично на:

2025
2025

Забелешка: Пример #7 Пристап до член на новосоздаден објект

Пред PHP 7.1, аргументите не се проценуваат ако не е дефинирана конструкторска функција.

Својства и методи

Својствата и методите на класата живеат во одделни „имиња простори“, така што е можно да имате својство и метод со исто име. Реферирањето до својство и метод има иста нотација, а дали ќе се пристапи својство или ќе се повика метод, зависи исклучиво од контекстот, т.е. дали употребата е пристап до променлива или повик на функција.

<?php
class Foo
{
public
$bar = 'property';

public function
bar() {
return
'method';
}
}

$obj = new Foo();
echo
$obj->bar, PHP_EOL, $obj->bar(), PHP_EOL;

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

property
method

Пример #8 Пристап до својство наспроти повик на метод анонимна функција Тоа значи дека повикувањето на

што е доделено на својство не е директно можно. Наместо тоа, својството мора прво да се додели на променлива, на пример. Можно е директно да се повика такво својство со затворање во загради.

<?php
class Foo
{
public
$bar;

public function
__construct() {
$this->bar = function() {
return
42;
};
}
}

$obj = new Foo();

echo (
$obj->bar)(), PHP_EOL;

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

42

extends

Пример #9 Повикување анонимна функција зачувана во својство extends Класата може да ги наследи константите, методите и својствата на друга класа со користење на клучниот збор

во декларацијата на класата. Не е можно да се прошират повеќе класи; класата може да наследи само од една основна класа. finalНаследените константи, методи и својства можат да бидат презапишани со нивно повторно декларирање со истото име дефинирано во родителската класа. Сепак, ако родителската класа дефинирала метод или константа како parent::.

Забелешка: , тие не можат да бидат презапишани. Можно е да се пристапи до презапишаните методи или статички својства со реферирање до нив со

Од PHP 8.1.0, константите можат да се декларираат како final.

<?php
class SimpleClass
{
function
displayVar()
{
echo
"Parent class\n";
}
}

class
ExtendClass extends SimpleClass
{
// Redefine the parent method
function displayVar()
{
echo
"Extending class\n";
parent::displayVar();
}
}

$extended = new ExtendClass();
$extended->displayVar();
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

Extending class
Parent Class

Правила за компатибилност на потпис

При препишување на метод, неговиот потпис мора да биде компатибилен со родителот метод. Во спротивно, се емитува фатална грешка, или, пред PHP 8.0.0, се генерира грешка од ниво. E_WARNING грешка од ниво. Потписот е компатибилен ако ги почитува variance правилата, прави задолжителен параметар опционален, додава само опционални нови параметри и не ја ограничува, туку само ја релаксира видливоста. Ова е познато како Принцип на замена на Лисков, или накратко LSP. На constructorПрепорачаниот начин за избегнување на SQL инјекција е со врзување на сите податоци преку подготвени изрази. Користењето на параметризирани прашања не е доволно за целосно избегнување на SQL инјекција, но тоа е најлесниот и најбезбедниот начин за обезбедување влез во SQL изразите. Сите динамични литерали на податоци во private методите се ослободени од овие правила за компатибилност на потпис и затоа нема да емитуваат фатална грешка во случај на несоодветност на потписот.

Пример #11 Компатибилни подкласни методи

<?php

class Base
{
public function
foo(int $a) {
echo
"Valid\n";
}
}

class
Extend1 extends Base
{
function
foo(int $a = 5)
{
parent::foo($a);
}
}

class
Extend2 extends Base
{
function
foo(int $a, $b = 5)
{
parent::foo($a);
}
}

$extended1 = new Extend1();
$extended1->foo();
$extended2 = new Extend2();
$extended2->foo(1);

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

Valid
Valid

Следниве примери покажуваат дека подкласен метод кој отстранува параметар или прави опционален параметар задолжителен, не е компатибилен со родителот метод.

Пример #12 Фатална грешка кога подкласен метод отстранува параметар

<?php

class Base
{
public function
foo(int $a = 5) {
echo
"Valid\n";
}
}

class
Extend extends Base
{
function
foo()
{
parent::foo(1);
}
}

Излезот од горниот пример во PHP 8 е сличен на:

Fatal error: Declaration of Extend::foo() must be compatible with Base::foo(int $a = 5) in /in/evtlq on line 13

Пример #13 Фатална грешка кога подкласен метод прави опционален параметар задолжителен

<?php

class Base
{
public function
foo(int $a = 5) {
echo
"Valid\n";
}
}

class
Extend extends Base
{
function
foo(int $a)
{
parent::foo($a);
}
}

Излезот од горниот пример во PHP 8 е сличен на:

Fatal error: Declaration of Extend::foo(int $a) must be compatible with Base::foo(int $a = 5) in /in/qJXVC on line 13
Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Преименувањето на параметарот на метод во подкласа не е некомпатибилност на потпис. Сепак, ова не се препорачува бидејќи ќе резултира со runtime Грешка if именувани аргументи се користат.

Пример #14 Грешка при користење именувани аргументи и преименувани параметри во подкласа

<?php

class A {
public function
test($foo, $bar) {}
}

class
B extends A {
public function
test($a, $b) {}
}

$obj = new B;

// Pass parameters according to A::test() contract
$obj->test(foo: "foo", bar: "bar"); // ERROR!

Горниот пример ќе прикаже нешто слично на:

Fatal error: Uncaught Error: Unknown named parameter $foo in /in/XaaeN:14
Stack trace:
#0 {main}
  thrown in /in/XaaeN on line 14

::class

На class клучниот збор исто така се користи за резолуција на името на класата. За да го добиете целосното квалификувано име на класа ClassName use ClassName::class. Ова е особено корисно со namespaced classes.

Пример #15 Резолуција на име на класа

<?php
namespace NS {
class
ClassName {
}

echo
ClassName::class;
}
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

NS\ClassName

Забелешка:

Резолуцијата на името на класата користејќи ::class е трансформација во време на компилација. Тоа значи дека во моментот кога е креиран стринг со името на класата, сè уште не се случило никакво авто-вчитање. Како последица, имињата на класите се прошируваат дури и ако класата не постои. Во тој случај не се издава грешка.

Пример #16 Резолуција на име на класа што недостасува

<?php
print Does\Not\Exist::class;
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

Does\Not\Exist

Од PHP 8.0.0, ::class може да се користи и на објекти. Оваа резолуција се случува во време на извршување, а не во време на компилација. Неговиот ефект е ист како повикување get_class() на објектот.

Решавање на имиња на објекти

<?php
namespace NS {
class
ClassName {
}

$c = new ClassName();
print
$c::class;
}
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

NS\ClassName

Безбедни методи и својства

Од PHP 8.0.0, својствата и методите исто така може да се пристапат со операторот "nullsafe" наместо: ?->. Операторот nullsafe работи исто како пристап до својство или метод како погоре, освен што ако објектот што се дереференцира е null then null ќе биде вратен наместо да се фрли исклучок. Ако дереференцирањето е дел од синџир, остатокот од синџирот се прескокнува.

Ефектот е сличен на завиткување на секој пристап во is_null() прво проверете, но покомпактен.

Оператор Nullsafe

<?php

// As of PHP 8.0.0, this line:
$result = $repository?->getUser(5)?->name;

// Is equivalent to the following code block:
if (is_null($repository)) {
$result = null;
} else {
$user = $repository->getUser(5);
if (
is_null($user)) {
$result = null;
} else {
$result = $user->name;
}
}
?>

Забелешка:

Операторот nullsafe најдобро се користи кога null се смета за валидна и очекувана можна вредност за враќање на својство или метод. За укажување на грешка, фрлањето исклучок е попосакувано.

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

aaron на thatone точка com
пред 18 години
I was confused at first about object assignment, because it's not quite the same as normal assignment or assignment by reference. But I think I've figured out what's going on.

First, think of variables in PHP as data slots. Each one is a name that points to a data slot that can hold a value that is one of the basic data types: a number, a string, a boolean, etc. When you create a reference, you are making a second name that points at the same data slot. When you assign one variable to another, you are copying the contents of one data slot to another data slot.

Now, the trick is that object instances are not like the basic data types. They cannot be held in the data slots directly. Instead, an object's "handle" goes in the data slot. This is an identifier that points at one particular instance of an obect. So, the object handle, although not directly visible to the programmer, is one of the basic datatypes. 

What makes this tricky is that when you take a variable which holds an object handle, and you assign it to another variable, that other variable gets a copy of the same object handle. This means that both variables can change the state of the same object instance. But they are not references, so if one of the variables is assigned a new value, it does not affect the other variable.

<?php
// Assignment of an object
Class Object{
   public $foo="bar";
};

$objectVar = new Object();
$reference =& $objectVar;
$assignment = $objectVar

//
// $objectVar --->+---------+
//                |(handle1)----+
// $reference --->+---------+   |
//                              |
//                +---------+   |
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="bar"
//
?>

$assignment has a different data slot from $objectVar, but its data slot holds a handle to the same object. This makes it behave in some ways like a reference. If you use the variable $objectVar to change the state of the Object instance, those changes also show up under $assignment, because it is pointing at that same Object instance.

<?php
$objectVar->foo = "qux";
print_r( $objectVar );
print_r( $reference );
print_r( $assignment );

//
// $objectVar --->+---------+
//                |(handle1)----+
// $reference --->+---------+   |
//                              |
//                +---------+   |
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="qux"
//
?>

But it is not exactly the same as a reference. If you null out $objectVar, you replace the handle in its data slot with NULL. This means that $reference, which points at the same data slot, will also be NULL. But $assignment, which is a different data slot, will still hold its copy of the handle to the Object instance, so it will not be NULL.

<?php
$objectVar = null;
print_r($objectVar);
print_r($reference);
print_r($assignment);

//
// $objectVar --->+---------+
//                |  NULL   | 
// $reference --->+---------+
//                           
//                +---------+
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="qux"
?>
kStarbe на gmail точка com
пред 8 години
You start using :: in second example although the static concept has not been explained. This is not easy to discover when you are starting from the basics.
johannes точка kingma на gmail точка com
пред 4 години
BEWARE! 

Like Hayley Watson pointed out class names are not case sensitive. 

<?php
class Foo{}
class foo{} // Fatal error: Cannot declare class foo, because the name is already in use
?>
As well as
<?php
class BAR{}
$bar = new Bar();
echo get_class($bar);
?> 

Is perfectly fine and will return 'BAR'.

This has implications on autoloading classes though. The standard spl_autoload function will strtolower the class name to cope with case in-sensitiveness and thus the class BAR can only be found if the file name is bar.php (or another variety if an extension was registered with spl_autoload_extensions(); ) not BAR.php for a case sensitive file and operating system like linux. Windows file system is case sensitive but the OS is not  and there for autoloading BAR.php will work.
Даг
пред 15 години
What is the difference between  $this  and  self ?

Inside a class definition, $this refers to the current object, while  self  refers to the current class.

It is necessary to refer to a class element using  self ,
and refer to an object element using  $this .
Note also how an object variable must be preceded by a keyword in its definition.

The following example illustrates a few cases:

<?php
class Classy {

const       STAT = 'S' ; // no dollar sign for constants (they are always static)
static     $stat = 'Static' ;
public     $publ = 'Public' ;
private    $priv = 'Private' ;
protected  $prot = 'Protected' ;

function __construct( ){  }

public function showMe( ){
    print '<br> self::STAT: '  .  self::STAT ; // refer to a (static) constant like this
    print '<br> self::$stat: ' . self::$stat ; // static variable
    print '<br>$this->stat: '  . $this->stat ; // legal, but not what you might think: empty result
    print '<br>$this->publ: '  . $this->publ ; // refer to an object variable like this
    print '<br>' ;
}
}
$me = new Classy( ) ;
$me->showMe( ) ;

/* Produces this output:
self::STAT: S
self::$stat: Static
$this->stat:
$this->publ: Public
*/
?>
wbcarts на juno точка com
пред 17 години
CLASSES and OBJECTS that represent the "Ideal World"

Wouldn't it be great to get the lawn mowed by saying $son->mowLawn()? Assuming the function mowLawn() is defined, and you have a son that doesn't throw errors, the lawn will be mowed. 

In the following example; let objects of type Line3D measure their own length in 3-dimensional space. Why should I or PHP have to provide another method from outside this class to calculate length, when the class itself holds all the neccessary data and has the education to make the calculation for itself?

<?php

/*
 * Point3D.php
 *
 * Represents one locaton or position in 3-dimensional space
 * using an (x, y, z) coordinate system.
 */
class Point3D
{
    public $x;
    public $y;
    public $z;                  // the x coordinate of this Point.

    /*
     * use the x and y variables inherited from Point.php.
     */
    public function __construct($xCoord=0, $yCoord=0, $zCoord=0)
    {
        $this->x = $xCoord;
    $this->y = $yCoord;
        $this->z = $zCoord;
    }

    /*
     * the (String) representation of this Point as "Point3D(x, y, z)".
     */
    public function __toString()
    {
        return 'Point3D(x=' . $this->x . ', y=' . $this->y . ', z=' . $this->z . ')';
    }
}

/*
 * Line3D.php
 *
 * Represents one Line in 3-dimensional space using two Point3D objects.
 */
class Line3D
{
    $start;
    $end;

    public function __construct($xCoord1=0, $yCoord1=0, $zCoord1=0, $xCoord2=1, $yCoord2=1, $zCoord2=1)
    {
        $this->start = new Point3D($xCoord1, $yCoord1, $zCoord1);
        $this->end = new Point3D($xCoord2, $yCoord2, $zCoord2);
    }

    /*
     * calculate the length of this Line in 3-dimensional space.
     */ 
    public function getLength()
    {
        return sqrt(
            pow($this->start->x - $this->end->x, 2) +
            pow($this->start->y - $this->end->y, 2) +
            pow($this->start->z - $this->end->z, 2)
        );
    }

    /*
     * The (String) representation of this Line as "Line3D[start, end, length]".
     */
    public function __toString()
    {
        return 'Line3D[start=' . $this->start .
            ', end=' . $this->end .
            ', length=' . $this->getLength() . ']';
    }
}

/*
 * create and display objects of type Line3D.
 */
echo '<p>' . (new Line3D()) . "</p>\n";
echo '<p>' . (new Line3D(0, 0, 0, 100, 100, 0)) . "</p>\n";
echo '<p>' . (new Line3D(0, 0, 0, 100, 100, 100)) . "</p>\n";

?>

  <--  The results look like this  -->

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=1, y=1, z=1), length=1.73205080757]

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=100, y=100, z=0), length=141.421356237]

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=100, y=100, z=100), length=173.205080757]

My absolute favorite thing about OOP is that "good" objects keep themselves in check. I mean really, it's the exact same thing in reality... like, if you hire a plumber to fix your kitchen sink, wouldn't you expect him to figure out the best plan of attack? Wouldn't he dislike the fact that you want to control the whole job? Wouldn't you expect him to not give you additional problems? And for god's sake, it is too much to ask that he cleans up before he leaves?

I say, design your classes well, so they can do their jobs uninterrupted... who like bad news? And, if your classes and objects are well defined, educated, and have all the necessary data to work on (like the examples above do), you won't have to micro-manage the whole program from outside of the class. In other words... create an object, and LET IT RIP!
Хејли Вотсон
пред 8 години
Class names are case-insensitive:
<?php
class Foo{}
class foo{} //Fatal error.
?>

Any casing can be used to refer to the class
<?php
class bAr{}
$t = new Bar();
$u = new bar();
echo ($t instanceof $u) ? "true" : "false"; // "true"
echo ($t instanceof BAR) ? "true" : "false"; // "true"
echo is_a($u, 'baR') ? "true" : "false"; // "true"
?>

But the case used when the class was defined is preserved as "canonical":
<?php
echo get_class($t); // "bAr"
?>

And, as always, "case-insensitivity" only applies to ASCII.
<?php
class пасха{}
class Пасха{} // valid
$p = new ПАСХА(); // Uncaught warning.
?>
moty66 на gmail точка com
пред 16 години
I hope that this will help to understand how to work with static variables inside a class

<?php

class a {

    public static $foo = 'I am foo';
    public $bar = 'I am bar';
    
    public static function getFoo() { echo self::$foo;    }
    public static function setFoo() { self::$foo = 'I am a new foo'; }
    public function getBar() { echo $this->bar;    }            
}

$ob = new a();
a::getFoo();     // output: I am foo    
$ob->getFoo();    // output: I am foo
//a::getBar();     // fatal error: using $this not in object context
$ob->getBar();    // output: I am bar
                // If you keep $bar non static this will work
                // but if bar was static, then var_dump($this->bar) will output null 

// unset($ob);
a::setFoo();    // The same effect as if you called $ob->setFoo(); because $foo is static
$ob = new a();     // This will have no effects on $foo
$ob->getFoo();    // output: I am a new foo 

?>

Regards
Motaz Abuthiab
Белешки за stdClass
пред 16 години
stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.
<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.
<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

(tested on PHP 5.2.8)
pawel точка zimnowodzki на gmail точка com
3 години пред
Although there is no null-safe operator for not existed array keys I found workaround for it: ($array['not_existed_key'] ?? null)?->methodName()
Џефри
пред 17 години
A PHP Class can be used for several things, but at the most basic level, you'll use classes to "organize and deal with like-minded data". Here's what I mean by "organizing like-minded data". First, start with unorganized data.

<?php
$customer_name;
$item_name;
$item_price;
$customer_address;
$item_qty;
$item_total;
?>

Now to organize the data into PHP classes:

<?php
class Customer {
  $name;          // same as $customer_name
  $address;       // same as $customer_address
}

class Item {
  $name;          // same as $item_name
  $price;         // same as $item_price
  $qty;           // same as $item_qty
  $total;         // same as $item_total
}
?>

Now here's what I mean by "dealing" with the data. Note: The data is already organized, so that in itself makes writing new functions extremely easy.

<?php
class Customer {
  public $name, $address;                   // the data for this class...

  // function to deal with user-input / validation
  // function to build string for output
  // function to write -> database
  // function to  read <- database
  // etc, etc
}

class Item {
  public $name, $price, $qty, $total;        // the data for this class...

  // function to calculate total
  // function to format numbers
  // function to deal with user-input / validation
  // function to build string for output
  // function to write -> database
  // function to  read <- database
  // etc, etc
}
?>

Imagination that each function you write only calls the bits of data in that class. Some functions may access all the data, while other functions may only access one piece of data. If each function revolves around the data inside, then you have created a good class.
Анонимен
пред 7 години
At first I was also confused by the assignment vs referencing but here's how I was finally able to get my head around it. This is another example which is somewhat similar to one of the comments but can be helpful to those who did not understand the first example. Imagine object instances as rooms where you can store and manipulate your properties and functions.  The variable that contains the object simply holds 'a key' to this room and thus access to the object. When you assign this variable to another new variable, what you are doing is you're making a copy of the key and giving it to this new variable. That means these two variable now have access to the same 'room' (object) and can thus get in and manipulate the values. However, when you create a reference, what you doing is you're making the variables SHARE the same key. They both have access to the room. If one of the variable is given a new key, then the key that they are sharing is replaced and they now share a new different key. This does not affect the other variable with a copy of the old key...that variable still has access to the first room
На оваа страница

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

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

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

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

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