PHP注意:试图获取非对象的属性'hash'

问题描述 投票:0回答:1

我想使用php-oop建立一个区块链网络。我已经将代码从this tutorial中的node.js转换为php-oop

我的区块链代码:

<?php
include './vendor/autoload.php';
use Elliptic\EC;
$ec = new EC('secp256k1');

class Blockchain {
    public $pendingTransactions;

public function constructor() {
    $this->chain = [$this->createGenesisBlock()];
    $this->difficulty = 2;
    $this->pendingTransactions = [];
}

public function createGenesisBlock() {
    return new Block("2020-5-2" , "Genesis Block", "0");
}

public function getLatestBlock() {
    return $this->chain[strlen($this->chain) - 1];
}

public function minePendingTransactions() {
    $block = new Block(date("Y-m-d"), $this->pendingTransactions, $this->getLatestBlock()->hash);
    $block->mineBlock(2);
    $this->chain[] = $block;
    $this->pendingTransactions = [];
}

class Block {

    public $hash;
    public function __construct($timestamp, $transactions, $previousHash = null) {
        $this->previousHash = $previousHash;
        $this->timestamp = $timestamp;
        $this->transactions = $transactions;
        $this->nonce = 0;
        $this->hash = $this->calculateHash();
    }

    public function calculateHash() {
        return hash("sha256", $this->previousHash.$this->timestamp.json_encode($this->transactions).$this->nonce);
    }
}

它向我显示此错误:

PHP Notice:  Trying to get property 'hash' of non-object in /home/istabraq/bctest/test2/a3.php on line 24

有什么帮助吗?建议,请吗?

php oop hash constructor blockchain
1个回答
0
投票

这里

public function getLatestBlock() {
    return $this->chain[strlen($this->chain) - 1];
}

您(不正确地)使用strlen()来获取数组的项数,以便返回$this->chain的最后一项(块)

改用count()

public function getLatestBlock() {
    return $this->chain[count($this->chain) - 1];
}
© www.soinside.com 2019 - 2024. All rights reserved.