Jump to content

Recommended Posts

I have done lots of class in C++ which is a very long time ago. I have never attempted this in php. Here is what I was looking at. Please not too crital over this but I am interested in pulic and private variables and functions here. Do  need to give values to the variables in the class?

<?php
Class Human
{
public string $Name ="";
public float $Height = 0.0;
public int Age = 0;
	
	public function WhoAmI()
	{
		private string $Details = "Name: . $Name . " Height:" . $Height . " Age:" . $Age;
		$this-> $Details
	}	
}

$PersonA = new Human;
$PersonA->$Name = "Philip";
$PersonA->$Height = 5.10;
$PersonA->$Age = 24;
echo $PersonA->WhoAmI;
?>

 

Edited by Paul-D
Link to comment
https://forums.phpfreaks.com/topic/330669-never-done-any-class-in-php/
Share on other sites

Noticed a few silly typos. Here is the latest.

<?php
Class Human
{
public string $Name ="";
public float $Height = 0.0;
public int $Age = 0;
	
	public function WhoAmI(): string
	{
		private string $Details = "Name:" . $Name . " Height:" . $Height . " Age:" . $Age;
		$this-> $Details;
	}	
}

$PersonA = new Human;
$PersonA->$Name = "Philip";
$PersonA->$Height = 5.10;
$PersonA->$Age = 24;
echo $PersonA->WhoAmI;
?>

 

Even better?

<?php
Class Human
{
public string $Name ="";
public float $Height = 0.0;
public int $Age = 0;
private string $Detals;

public function __construct(float $Heiht, int $Age, string $Name = "Billy")
{
	$this->Height = $Height;
	$this->Age = $Age;
	$this->Name = $Name;
}

function __destruct() 
{
	// nothing to see here
}
	
	public function WhoAmI(): string
	{
		$Details = "Name:" . $Name . " Height:" . $Height . " Age:" . $Age;
		return $this->Details;
	}	
}

$PersonA = new Human;
$PersonA->$Name = "Philip";
$PersonA->$Height = 5.10;
$PersonA->$Age = 24;
echo $PersonA->WhoAmI;

$PersonB = new Human(5.10, 52);
echo $PersonB->WhoAmI // Name will be Billy
?>

 

Edited by Paul-D

Your code is error prone and hard to read because you aren't following code standards.  

I recommend you read through this standard:  https://www.php-fig.org/per/coding-style/

To begin with, your variables and functions/methods should all be camel case.   

You should NOT have a php end tag at the bottom of any script.  PHP doesn't need it, and it can introduce issues that are hard to debug.   This is also mentioned in the coding standards I linked for you. 

$Height // wrong
$height // right

$Age // wrong
$age // right

$Business_address //wrong
$businessAddress; //right

public function WhoAmI() // wrong
public function whoAmI() // right


When you call a function or a method, you should always be using parens!

$person->whoAmI    // wrong
$person->whoAmI(); // right

 

The best practice for class definitions, is that you should have a script for each class with the same name as the class.  In your example, I would make a script named "Human.php".

You can then "require "Human.php" in your code, although these days people use the composer tools to manage apps, and will have an autoloader for classes using namespace definitions. 

PHP is not different conceptually from c++ in regards to some core OOP concepts like data hiding. 

You are making your class variables public.  Don't do that.  They should all be private.  You can then implement getters/setters, or PHP has magic methods you can use.

When you instantiate an object with "new" you need to pass the constructor parameters to it.  Here is your code rewritten to be closer to what it should be.

<?php
class Human
{
    private string $name = "";
    private float $height = 0.0;
    private int $age = 0;

    public function __construct(float $height, int $age, string $name = "Billy")
    {
    	$this->height = $height;
    	$this->age = $age;
    	$this->name = $name;
    }

    public function whoAmI(): string
    {
        $details = "Name: " . $this->name . " Height: " . $this->height . " Age: " . $this->age;
        return $details;
    }	
}

$personA = new Human(5.1, 24, 'Philip');
echo $personA->whoAmI() . PHP_EOL;


$personB = new Human(5.10, 52);
echo $PersonB->whoAmI();// Name will be Billy

You rarely need to have a  destructor, and you certainly don't want to have an empty one.  PHP destructs things automatically for you (garbage collection).

You might want to look at the newer features in PHP 8 that allow you to use Attributes in place of the boilerplate constructor assignments and constructor setters. 

Variables Like $Age and $TinsOfCatFood would not cause a php error. It makes for good reading and is widely used within the Visual C++ world. Yes, php is case sensitive and $Cat and $cat would be different. You just have to set a standard for your variables and keep to it. You can use the laid down php standard if you wish.

Scope of a variable is defiantly important. If a class variable has to be accessed outside the class, it MUST be public. I am accessing the variable $Age but I also have a private variable, private string $Detals. This cannot be accessed outside the class but can be returned as a value from the calling function.

I have in part is taken this from the PHP Manual https://www.php.net/manual/en/language.oop5.properties.php

Here we have within a class public $var1 = 'hello ' . 'world' also we have public $var6 = myConstant;

As for having a class Human.php this does make good sense but this was my first attempt at using php. I could also have a  DefaultClasses.php with the main classes held within it. Microsoft do this.

The only criticism I see is PHP does not allow function overloading which is a setback. All in all, this should not cause a php error only my C++ standards differ here.

I am confused with your tags are you saying that in php you should start with <?php but leave out the closing ?> at the end? This is a definite NO NO.

PHP manual https://www.php.net/manual/en/language.oop5.visibility.php

<?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

 

4 hours ago, Paul-D said:

Variables Like $Age and $TinsOfCatFood would not cause a php error. It makes for good reading and is widely used within the Visual C++ world. Yes, php is case sensitive and $Cat and $cat would be different. You just have to set a standard for your variables and keep to it. You can use the laid down php standard if you wish.

I didn't say they would cause an error, I said they were not the standard for variable, class and function naming, which makes them error prone.  You should follow a convention so that other people can read and understand your code, and you don't have to think to hard about how to name a variable.  This is why I re-wrote the code for you.  If you're going to pick up on what people are trying to teach you, you have to look at the code they provided you and compare it to your code, and study it.

4 hours ago, Paul-D said:

 

Scope of a variable is defiantly important. If a class variable has to be accessed outside the class, it MUST be public. I am accessing the variable $Age but I also have a private variable, private string $Detals. This cannot be accessed outside the class but can be returned as a value from the calling function.

 

Yes you can make class variables public.  You SHOULD NOT do that.  As I mentioned, this is because, you want to implement the concept of "Information/Data Hiding" and the associated concept of "Encapsulation".  In other words, you should not allow the core code or other classes to directly access class variables.  Doing so creates code that is "tightly coupled" which as another thing you want to avoid.  There are many ways to implement the internal representation of data, and the users of the class should not depend on the internal representation, which is why you use getter/setter methods instead, or in your case, a method like "whoAmI()"

Again, these are all things I think you would have encountered when writing C++ Oop.  You might want to do some research on your own, in order to understand what I'm trying to help you understand.

  • Data Hiding
  • Encapsulation
  • Tight coupling vs Loose Coupling

 

4 hours ago, Paul-D said:

As for having a class Human.php this does make good sense but this was my first attempt at using php. I could also have a  DefaultClasses.php with the main classes held within it. Microsoft do this.

PHP Oop goes hand in hand with PHP Namespaces, PHP application development and project structuring using Composer, and class Autoloading.  Once you layout and structure your code in a conventional way, you can take advantage of Autoloading, and one thing composer does for you, when you understand how to use it, is it will generate the autoloader include for you, and you can include it in your code.    This only makes sense once you understand and start to use Namespaces, but it is how professional PHP development is done now.

 

4 hours ago, Paul-D said:

As for having a class Human.php this does make good sense but this was my first attempt at using php. I could also have a  DefaultClasses.php with the main classes held within it. Microsoft do this.

 Again, what you can do and what you SHOULD do are different.  I'm trying to help you understand how you SHOULD code, which will save you time, and get you to a level of understanding and competency. 

4 hours ago, Paul-D said:

The only criticism I see is PHP does not allow function overloading which is a setback. All in all, this should not cause a php error only my C++ standards differ here.

Correct, PHP does not have operator overloading.  It also differs from c++ in many other ways, being loosely typed, doesn't have multiple inheritance, or templates.  It also runs in virtual machine, does all memory allocation and garbage collection for you, etc.  With that said, what you can do is implement common OOP design patterns like "Dependency Injection" and the many other patterns codified in the Gang of Four book.

 

5 hours ago, Paul-D said:

 

I am confused with your tags are you saying that in php you should start with <?php but leave out the closing ?> at the end? This is a definite NO NO.

 

 

Yes, I'm telling you that exact thing.  You don't need an end tag, and you should not have an end tag in your PHP scripts.   

The ONLY time you need to use the php end tag is when you have a script that intermixes HTML with PHP, and even in that case, you should not have a PHP end tag at the bottom of your script. 

In general, the intermixing of PHP and HTML, is something to avoid, in order to maintain "seperation of concerns" and implement popular web application design patterns like "Model View Controller (MVC)", which is what the most popular PHP frameworks do.

PHP has long supported template libraries going back to "Smarty", and these MVC frameworks (Laravel, Symfony, CodeIgniter, etc) all provide "Views" with template libraries, where you use their specific template system.  

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.