How to make member functions constant in PhP? [closed]

0

I was studying what my book called "constant member functions" in C ++. that is, functions that can not change any attribute of the class or call other methods that are not constants. So I made this code in C ++.

#include <iostream>
#include <string>

using namespace std;


class Foo
{
     string outra_coisa;
  public: 
    void printa_algo(string algo) const;
};

int main()
{
    Foo tolo;
    string alguma_coisa = "coisa_alguma";
    tolo.printa_algo(alguma_coisa);

    return 0;
}

void Foo::printa_algo(string algo) const
{
    cout << algo;
}

Is it possible to do the same in PHP ?

    
asked by anonymous 27.07.2017 / 02:03

2 answers

-1

Well after some research I saw in a book that is not possible, at least not trivial , create such functions in PhP. You can create methods that do not changes in attributes, but you can not create methods that can not make changes at all.

    
27.07.2017 / 06:28
0

I think you are referring to static functions, which can be called without creating an instance of the class, and which can not modify properties and members of it, if it is, just use the keyword static :

<?php
class Foo {
    public static function Bar() {
        echo 'Olá, mundo!';
    }
}

// você pode chamar assim
Foo::Bar();

// ou assim
$classname = 'Foo';
$classname::Bar();

// mas não assim
$class = new Foo;
$class->Bar(); // erro
?>
    
27.07.2017 / 06:03